Binding is the process of setting parameter values when Web API calls the controller How to do it.
Web API methods with different types of parameters and how to customize them Binding process.
If the parameter is a simple type such as int, bool, double, etc., Web API will try to get the value from the URI (from routing data or from the query string)
If the parameter is a complex type, such as Customer , Employee, etc., then Web API The framework attempts to get the value from the request body.
We can change the default behavior of the parameter binding process using the following method [FromBody] and [FromUri] properties.
FromUri -
If the parameter is a simple type, Web Api will try to get it from URI
.NET basic types, such as double, DateTime, GUID String, any type that can be used Converting from String type
public Student Get(int id){}
If the parameter type is Complex type, then Web Api will try to bind the value from Message text.
Public Student Post(Employee employee){}
To force the Web API to read complex types from the URI, add the [FromUri] attribute To the parameters
Use the [FromUri] attribute to force the Web Api to get the value of type Complex from Query string.
public Student Get([FromUri] Employee employee) public HttpResponseMessage Get([FromUri] Employee employee) { ... }
Use the [FromBody] attribute to get the Primitive type value from the request body, Contrary to the default
No, multiple FormBody is not allowed in a single operation.
To force Web API to read a simple type from the request body, add [FromBody]
In this example, Web API will use the media type formatter to read the value of name From request body
public Student Post([FromBody] string name]){...} public HttpResponseMessage Post([FromBody] string name) { ... }
The above is the detailed content of What is parameter binding in C# ASP.NET WebAPI?. For more information, please follow other related articles on the PHP Chinese website!