This paper will outline how to bind parameters to an action method in WebAPI mode, including how to read parameters, and a series of rules determine the binding method adopted in a specific environment. Finally, the article will give some examples.
After all, parameter binding is to receive an Http request and convert it into. NET type makes the signature of the operation method easier to understand.
The request message includes all the requested information, such as the request address (URL) with the query string, the content body and the header information. No parameter binding.
In the case of, each operation method needs to receive the request message and manually extract parameters from it, as shown below:
The public object myaction (http request message request) {//is explicitly called to get parameters from the request object int id = int. Parse (request. RequestUri.ParseQueryString()。 get(" id ")); //Need error logic! Customer c = request. Content.ReadAsAsync()。 Results; //should be asynchronous! //Use id and customer now}
Obviously, this method is ugly, error-prone, repetitive, and difficult for unit testing. We want the signature of the action to look like this:
Public object MyAction(int id, Customer c) {}
So how does WebAPI convert the request message into parameters such as id and customer?
Model binding and formatter
There are two techniques for parameter binding: model binding and formatter. In fact, WebAPI uses model binding to read the content of the query string for parameter binding, and uses formatter to read the main content.
(body content) to bind parameters.
Use model binding:
This concept is consistent in ModelBinding and MVC. See here for more details. There is usually a "ValuePeoviders" that provides data fragments such as query string parameters, and the model binder combines these fragments into an object.
Use the formatter:
Formatters (as shown in the MediaTypeFormatter class) are actually serializers that contain extra metadata. WebAPI gets the formatter list from HttpConfiguration and then passes the request information.
Type to determine the appropriate formatter. WebAPI has many default formatters. The default JSON formatter is JSON.NET. There are also Xml formatters and JQuery syntax.
FormUrl formatter.
The core method of formatter is mediatypeformatter. Readfromstreamsync, as shown in the following figure:
Public virtual task ..