ASP. NET Web API model-parameterbinding

Source: Internet
Author: User

ASP. NET Web API model-parameterbinding Preface

Learn the basics of model binding in the last space, however, the model binding function module is not called directly in the ASP., but rather, it is encapsulated by a series of objects parameterbinding the content to be described in this article. Through this study, you will probably know how to bind in the Web API.

Model-parameterbinding (Object article)

In the ASP. Parameterbinding represents a parameter binding and there are several ways in which the bindings are involved, however parameterbinding is not executed alone, as there may be multiple parameters in a controller method, So let's take a look at the related objects of actionbinding, and we'll talk about the resulting environment and process for these objects in the following space.

Httpactionbinding

Code 1-1

namespacesystem.web.http.controllers{ Public classhttpactionbinding { Publichttpactionbinding ();  Publichttpactionbinding (Httpactiondescriptor actiondescriptor, httpparameterbinding[] bindings);  PublicHttpactiondescriptor Actiondescriptor {Get;Set; }  PublicHttpparameterbinding[] Parameterbindings {Get;Set; }  Public VirtualTask Executebindingasync (httpactioncontext actioncontext, CancellationToken cancellationtoken); }}

In code 1-1, for the definition of the httpactionbinding type, see Httpactionbinding types of overloaded constructors have httpactiondescriptor types, Httpparameterbinding type array type as parameter, Httpactiondescriptor type as Controller method description type you are already familiar with it, this type contains the meta-data information of the Controller method, While the latter httpparameterbinding type is a parameter binding object, in fact, the binding of each parameter in the model binding is through parameterbinding binding, so the execution of the process here we do not go into the deep understanding, is simply to understand the relevant object model.

Httpparameterbinding

Code 1-2

namespacesystem.web.http.controllers{ Public Abstract classhttpparameterbinding {protectedhttpparameterbinding (httpparameterdescriptor descriptor);  PublicHttpparameterdescriptor Descriptor {Get; }  Public Virtual stringerrormessage {Get; }  Public BOOLIsValid {Get; }  Public Virtual BOOLWillreadbody {Get; }  Public AbstractTask Executebindingasync (Modelmetadataprovider metadataprovider, Httpactioncontext Actioncontext,        CancellationToken CancellationToken); protected ObjectGetValue (Httpactioncontext actioncontext); protected voidSetValue (Httpactioncontext Actioncontext,Objectvalue); }}

In code 1-2 we see the definition of the httpparameterbinding type, we can see that httpparameterbinding is an abstract type, and the method of implementing the binding Executebindingasync () is also abstract, This is to be in different circumstances and circumstances love to take a different binding mechanism to pave the way is multi-state, this we will say, we still first look at the httpparameterbinding type of internal definition, first we see is the constructor of the parameter type, Httpparameterdescriptor type, another object description type, this time the description object is to control a parameter in its method, The Httpparameterbinding object instance is generated based on the Httpparameterdescriptor object instance, which is explained in the following space. The ErrorMessage property represents an error message that occurs during parameterbinding binding, and the IsValid property indicates whether the binding can be done by determining whether the ErrorMessage property is null. The Willreadbody property indicates whether the Parameterbinding object reads the HTTP message body content as a parameter-bound data source, which is seen later in the example. The GetValue () and SetValue () methods are to get the corresponding parameter value and set the parameter corresponding value to the current httpactioncontext.

Modelbinderparameterbinding

Code 1-3

namespacesystem.web.http.modelbinding{ Public classmodelbinderparameterbinding:httpparameterbinding, ivalueproviderparameterbinding { PublicModelbinderparameterbinding (httpparameterdescriptor descriptor, Imodelbinder Modelbinder, IEnumerable< System.web.http.valueproviders.valueproviderfactory>valueproviderfactories);  PublicImodelbinder Binder {Get; }  PublicIenumerable<system.web.http.valueproviders.valueproviderfactory> Valueproviderfactories {Get; }  Public OverrideTask Executebindingasync (Modelmetadataprovider metadataprovider, Httpactioncontext Actioncontext,    CancellationToken CancellationToken); }}

Code 1-3 represents the Modelbinderparameterbinding type, which represents the binding method (the data source of the binding) is obtained through Imodelbinder, and just as the constructor we see in code 1-3, There are collections of Imodelbinder and valueproviderfactory types, which are data-bound data sources. The Binder property and the Valueproviderfactories property are the two type values passed in by the constructor. There's not much to say about bindings.

Formatterparameterbinding

Code 1-4

namespacesystem.web.http.modelbinding{ Public classformatterparameterbinding:httpparameterbinding { PublicFormatterparameterbinding (Httpparameterdescriptor descriptor, ienumerable<mediatypeformatter>formatters, Ibodymodelvalidator bodymodelvalidator);  PublicIbodymodelvalidator Bodymodelvalidator {Get;Set; }  Public Override stringerrormessage {Get; }  Publicienumerable<mediatypeformatter> formatters {Get;Set; }  Public Override BOOLWillreadbody {Get; }  Public OverrideTask Executebindingasync (Modelmetadataprovider metadataprovider, Httpactioncontext Actioncontext,        CancellationToken CancellationToken);  Public Virtualtask<Object> Readcontentasync (httprequestmessage request, type type, ienumerable<mediatypeformatter>formatters, Iformatterlogger Formatterlogger); }}

How does the formatterparameterbinding type shown in code 1-4 get the binding data source? You can see that the Willreadbody property is overridden in this type, and the default in the Httpparameterbinding type is not to read or write the contents of the HTTP request. And here in the formatterparameterbinding type, has been rewritten, indicating that in this type we can use the binding data source is from the HTTP request body content to read, but the body content of the HTTP request is not directly placed there for us to read, Instead, it is serialized by the specified serializer before the client sends it.

Then we have to deserialize on the server side to get the value, here in code 1-4 we see the constructor can see and code 1-3 is a httpparameterdescriptor type of parameter object, Then it is a collection object of the Mediatypeformatter type, and finally the object for model validation, which is followed.

Now let's take a look at the Mediatypeformatter type in the second parameter type.

Mediatypeformatter

Code 1-5

namespacesystem.net.http.formatting{ Public Abstract classMediatypeformatter {protectedMediatypeformatter ();  Public Abstract BOOLcanreadtype (type type);  Public Abstract BOOLcanwritetype (type type);  Public Virtualtask<Object>readfromstreamasync (Type type, Stream readstream, httpcontent content, Iformatterlogger Formatterlogger);  Public VirtualTask writetostreamasync (Type type,Objectvalue, Stream writestream, httpcontent content, TransportContext transportcontext); }}

The Mediatypeformatter type shown in code 1-5 is part of the cut, and the remaining 4 methods are two abstract methods, two are virtual methods, first look at the definition of two abstract methods, Canreadtype () The Canwritertype method represents whether the value of the modified type can be read from the current HTTP request body according to the specified parameter type, which is simply the ability to deserialize the body content into the specified parameter type, and the same as the response body. The Readfromstreamasync () method and the Writetostreamasync () method are two ways to actually manipulate HTTP request Body content and HTTP response body content.

Implementation types for mediatypeformatter types such as jsonmediatypeformatter for JSON format and xmlmediatypeformatter for XML format.

Let's take a look at a simple example of the Jsonmediatypeformatter type, and everyone will know what's going on.

First we define a method to receive the post request in the server-side controller,

Code 1-6

        [Customcontrolleractionauthorizationfilter]        publicvoid  Post (Product Product)        {products            . ADD (product);        }

To facilitate the demonstration, an authorization filter has been added to its control method. We then use the Jsonmediatypeformatter type for the processing of the post request to deserialize the Customcontrolleractionauthorizationfilter filter type.

Code 1-7

 PublicTask<system.net.http.httpresponsemessage> Executeauthorizationfilterasync ( System.Web.Http.Controllers.HttpActionContext Actioncontext, System.Threading.CancellationToken CancellationToken , func<task<system.net.http.httpresponsemessage>>continuation)            {Console.WriteLine (ActionContext.Request.Content.Headers.ContentType.MediaType); IEnumerable<MediaTypeFormatter> formatters =Newmediatypeformatter[] {Newjsonmediatypeformatter ()}; Product Product= actioncontext.request.content.readasasync<common.product>(formatters).            Result; Console.WriteLine (product.            ProductID); Console.WriteLine (product.            ProductName); Console.WriteLine (product.            ProductCategory); returncontinuation (); }

In code 1-7, the authorization filter is passed before the request arrives at the controller method, in which we first output the current request's format type to the server-side controller, and then use the Jsonmediatypeformatter type for the body content of the current request to deserialize the operation.

Let's look at the client using the HttpClient type for the analog POST request.

Code 1-8

HttpClient HttpClient =NewHttpClient (); Product Product=NewProduct () {ProductID="003", ProductName="Mong Tsai Milk", ProductCategory="Food category"            }; awaitHttpclient.postasjsonasync<product> ("http://localhost/selfhost/api/product", product);

Final result 1.

Figure 1

See here presumably everyone also know how to use the way of xmlmediatypeformatter.

There is also a mediatypeformatter type Formurlencodedmediatypeformatter type, and the Formurlencodedmediatypeformatter type represents the HTTP The format used for the data submitted by the form in the POST request, let's take a look at the implementation of the Canreadtype () method in the Formurlencodedmediatypeformatter type.

Code 1-9

     Public Override BOOLcanreadtype (Type type) {if(Type = =NULL)        {            ThrowError.argumentnull ("type"); }        if(! (Type = =typeof(formdatacollection))) {            returnFormattingutilities.isjtokentype (type); }        return true; }

In code 1-9 we can see that the formdatacollection type is actually an object of type ienumerable<keyvaluepair<string, string>>, In the request URL after the form is submitted, you can also see that it is the form of key=value, so this is the format. For the example of this format, we will give you a demonstration in the following space.

Httprequestparameterbinding

Finally, let's look at a Requestparameterbinding object.

Code 1-10

     Public classhttprequestparameterbinding:httpparameterbinding {//Methods         Publichttprequestparameterbinding (httpparameterdescriptor descriptor):Base(descriptor) {} Public OverrideTask Executebindingasync (Modelmetadataprovider metadataprovider, Httpactioncontext Actioncontext, CancellationToken cancellationtoken) {stringParameterName =Base.            Descriptor.parametername; Httprequestmessage Request=actionContext.ControllerContext.Request;            ACTIONCONTEXT.ACTIONARGUMENTS.ADD (parametername, request); returntaskhelpers.completed (); }    }

In code 1-10 we see the implementation of the Executebindingasync () method, which is obtained directly into the parameter name and the current request object, and then added to the Actionarguments property that controls its method execution context. In the previous space, it was also said that this property is used to store the method corresponding to the parameter value (the model bound value).

This article about the parameterbinding of the introduction to here, are fragmented, but in the later space there will be an example of the explanation.

Jinyuan

Source: http://www.cnblogs.com/jin-yuan/

This article is copyrighted by the author and the blog Park, welcome reprint, but without the consent of the author must retain this statement, and on the article page

ASP. NET Web API model-parameterbinding

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.