ASP. NET Web API model-actionbinding

Source: Internet
Author: User

ASP. NET Web API model-actionbindingPreface

some of the previous pages have The model part of the knowledge points divided into a module to explain, and in the controller implementation process is divided into a lot of processes, for the controller execution process ( a ) mainly explained the filter and in the back of the filter space is also mentioned, And in the filter there are some execution process, that is, after the authorization filter execution, the behavior filter execution, we have to do is the model binding, before also said before the model of the Knowledge Point module is explained almost, Today we'll look at the source of these scattered points of knowledge, the entry point of Model bindings.

Model-actionbinding

httpactionbinding origin of

we know through the previous few understanding that in The entry point into the entire Model binding in the ASP. NET Web API Framework is in the httpactionbinding type, which is described in the previous space of this type, which encapsulates Parameterbinding Arrays, these parameterbinding are the objects in the Controller method that perform the Model binding for each parameter , since we know There are many instances of parameterbinding types in the httpactionbinding type , so we'll look at how the httpactionbinding type is generated.

Example code 1-1

This. Setsingle<iactionvaluebinder> (New Defaultactionvaluebinder ());

First we see the example code 1-1 in the httpconfiguration type of service container, which is registered as the Iactionvaluebinder type service by default. The Defaultactionvaluebinder type.

Example code 1-2

Namespace system.web.http.modelbinding{public class Defaultactionvaluebinder:iactionvaluebinder {public D        Efaultactionvaluebinder ();        Public virtual httpactionbinding getbinding (Httpactiondescriptor actiondescriptor);    Protected virtual httpparameterbinding getparameterbinding (httpparameterdescriptor parameter); }}


Code1-2is shown in theDefaultactionvaluebinderThe definition of a type, where these two methods are important, the firstGetbinding ()method is used within the framework to make calls, depending onHttpactiondescriptorThe Controller method description type Object gets to what we needHttpactionbinding, and its internal implementation is to invoke the followingGetparameterbinding ()method, usingHttpactiondescriptorobject gets toHttpparameterdescriptorafter the collection, and then traverse the go callGetparameterbinding ()Method,To gain access toHttpparameterbindingobject instance, which is finally generatedHttpactionbindingobject instance, from a design point of view.Defaultactionvaluebindertwo methods in a typeGetbinding ()and theGetparameterbinding ()methods are all based on theTemplatemethodmode, which is common in frame design.

httpparameterbinding origin of

We're going to talk about it. the details of the getparameterbinding () method are implemented because of the way in which the bindings are used. that is, according to the Httpparameterdescriptor type instance how to create httpparameterbinding .

Example code 1-3

    protected virtual httpparameterbinding getparameterbinding ( Httpparameterdescriptor parameter)     {         parameterbindingattribute parameterbinderattribute = parameter. parameterbinderattribute;        if  (ParameterBinderAttribute  == null)         {             parameterbindingrulescollection parameterbindingrules = parameter . Configuration.parameterbindingrules;            if   (Parameterbindingrules != null)              {                 Httpparameterbinding binding = parameterbindingrules.lookupbinding (parameter);                 if  (binding != null)                  {                     return binding;                 }             }            type  parametertype = parameter. parametertype;            if  ( Typehelper.issimpleunderlyingtype (parametertype)  | |  typehelper.hasstringconverter (parametertype))              {                 return parameter. Bindwithattribute (New fromuriattribute ());             }            parameterbinderattribute  = new frombodyattribute ();        }         return parameterbinderattribute.getbinding (parameter);      }

Code 1-3 is a concrete implementation, so let's take a look at the process and the types involved.

The first is based on the parameters The Httpparameterdescriptor type instance gets the Parameterbindingattribute identity used on this controller method parameter , and gets An instance of the Parameterbindingattribute type. Let 's take a look at the Parameterbindingattribute type definition for a moment .

Example code 1-4

[AttributeUsage (Attributetargets.parameter | AttributeTargets.Class, inherited = True, AllowMultiple = false)] public abstract Class Parameterbindingattribute:att        Ribute {//Methods protected parameterbindingattribute ();    Public abstract httpparameterbinding getbinding (httpparameterdescriptor parameter); }


As can be seen from code 1-4, this parameterbindingattribute type is suitable for types and parameters, that is, the way we choose to bind is in the model When the type is defined, it is also possible to identify the parameter as appropriate when defining the Controller method.

However, in this type, why do you have What about the Getbinding () method? Because this type is an abstract type, that is , the template method pattern mentioned above is used, and in the subclass implementation, the httpparameterbinding type of the response is generated according to the circumstances of its own adaptation . Look at the following diagram to represent the related object model.

Figure 1

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/4A/43/wKiom1QkAmWB6y-1AAFXRa7CSws421.jpg "title=" Modelbinder1.png "width=" 738 "height=" 237 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" WIDTH:738PX;HEIGHT:237PX; "alt=" Wkiom1qkamwb6y-1aafxra7csws421.jpg "/>

Each of the types involved in Figure 1 above can be seen in front of the space, the length of the omission of the trouble everyone to move their hands to see it.

httpparameterbinding the selection mechanism

then the code 1-3 Thoughts, after we have obtained the Parameterbindingattribute , do not know whether the parameters in this controller method are identified Parameterbindingattribute, or whether there is an identity on the parameter type. This time if there is, you can see the code 1-3 The last line of code, directly using the Parameterbindingattribute type obtained to call getbinding () method, as shown in Figure 1 in the previous section .

However, there is a situation where we define the controller method with no explicit identification of the parameters we want to use some kind of binding mechanism, or to define The Model does not have a clear representation, and this time the framework obtains the corresponding Parameterbinding type instance from the defined set of rules based on the type of description currently controlling its method parameters . The following example code defines the definition of a rule collection.

Example code 1-5

    internal static ParameterBindingRulesCollection  Getdefaultparameterbinders ()     {         Parameterbindingrulescollection ruless = new parameterbindingrulescollection ();         ruless. Add (typeof (CancellationToken),  parameter => new cancellationtokenparameterbinding ( parameter));         ruless. Add (typeof (Httprequestmessage),  parameter => new httprequestparameterbinding (parameter) );         ruless. ADD (delegate  (httpparameterdescriptor parameter)  {             if  (!typeof (httpcontent). IsAssignableFrom (parameter. ParameterType))             {                 return null;             }             return parameter. Bindaserror (Error.format (srresources.parameterbindingillegaltype, new object[] { parameter . Parametertype.name, parameter. parametername }));         });         return ruless;     }


Code1-5is defined in the rules, meaning that we use theHttpparameterdescriptortype instance to get from the collectionParameterbindingthe time,Parameterbindingrulescollectiontype will put ourHttpparameterdescriptorin the type instance.ParameterTypeis removed to match the type of each rule defined previously, and the type matches the corresponding delegate type to be calledParameterbindinggenerated. From the Code1-5we can see in the rules that onlyCancellationTokenTypes andHttprequestmessagetype, if at this time our control method parameter type is a custom complex type, there is no definition here, this time the framework will take outHttpparameterdescriptorin the typeParameterTypeTo be judged, if it is to be converted intoStringtype is a simple type parameter, aFromuriattributetype as the identity,Fromuriattributetype inherits fromModelbinderattributetype.

If the judgment here is not passed, then it is a complex type, and finally we look at the definition in code 1-3, the final generation is the Frombodyattribute identity type, this time please refer to Figure 1.


This article is from the "Jinyuan" blog, please be sure to keep this source http://jinyuan.blog.51cto.com/8854733/1558338

ASP. NET Web API model-actionbinding

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.