In WebAPI, the request body (HttpContent) can only be read once, not cached, and can only be read forward.
For example:
1. Request address: /?id=123&name=bob
Server-side method: void Action(int id, string name) // All parameters are simple types, so they will all come from the url
2. Request address: /?id=123&name=bob
Server-side method: void Action([FromUri] int id, [FromUri] string name) // Same as above
void Action([FromBody] string name); The [FormBody] attribute displays that the entire body is read as a string as an argument
3. Request address: /?id=123
Class Definition:
public class Customer { // A complex object type defined public string Name { get; set; } public int Age { get; set; }
}
Server-side method: void Action(int id, Customer c) // Parameter id is read from the query string, parameter c is a complex Customer object class, read from body through formatter
Server-side method: void action(Customer c1, Customer c2) // Error! Multiple parameters are complex types and all try to read from a body, which can only be read once
Server-side method: void action([FromUri] Customer c1, Customer c2) // Yes! Unlike the action above, complex type C1 will be read from the URL and C2 will be read from the body
4.ModelBinder method:
void Action([ModelBinder(MyCustomBinder)] SomeType c) // Indicates that a specific model binder is used to resolve the parameter
[ModelBinder(MyCustomBinder)] public class SomeType { } // Apply this rule to all SomeType type parameters by declaring the [ModelBidner(MyCustomBinder)] attribute to a specific type SomeType
void Action(SomeType c) // Since the type of c is SomeType, the characteristics on SomeType are applied to determine its model binding
Summary:
1. The default simple parameters are passed through URL parameters, with exceptions:
1.1 If the route contains the id parameter, the id parameter is passed through the route;
1.2 If the parameter is marked as [FromBody], the parameter can be a simple parameter, and the client can pass it via POST: $.ajax(url, '=value'), or $.ajax({url: url, data: {'': 'value'}});
2. The default complex parameters (custom entity classes) are passed via POST, with exceptions:
2.1 If the parameter value is marked as [FromUri], the parameter can be a complex parameter;
3. A parameter marked [FromBody] is allowed to appear only once, a parameter marked as [FromUri] can appear multiple times, and if the parameter marked as [FromUri] is a simple parameter, the tag can be removed. |