ASP.NET Web API Parameter vs Model Binding






4.79/5 (6 votes)
The differences between parameter and model binding with ASP.NET WebAPI
Background
ASP.NET WebAPI follows these default rules for binding:
- If the parameter is a primitive type such as an integer, string or boolean, it will attempt to use parameter binding first, in the absence of any other directive.
- Complex types will default to reading the values from the request body in the absence of any other directive.
- Complex types can use parameter binding with the correct directive in the method argument.
ASP.NET WebAPI supports two different directives for indicating where the data should be bound from:
[FromUri]
- This directive tells the method that the data can be found in the request URL.[FromBody]
- This directive tells the method that the data can be found in the request body.
Examples
Below are two simple examples of the different types of binding, the first from the URI and the second from the body of the request:
public ProductController : ApiController
{
[HttpGet]
[Route("Product/{id}")]
public HttpResponseMessage GetProductById([FromUri] int productId )
{
// Code here for the controller method
}
}
The Request
URL would look something like https://localhost/api/product/100.
public ProductController : ApiController
{
[HttpPost]
[Route("Product")
public HttpResponseMessage AddProduct([FromBody] Product newProduct )
{
// Code here for the controller method
}
}
The Request
would look like this when using POSTMAN.
Points of Interest
Generally, not strictly speaking, Http verbs for Put
and Post
use a model in the body of the request, as they are either creating or updating a resource and sometimes can require a large model that would be unwieldy in the URI.
HttpGet
and Delete
verbs typically will use the URI as generally speaking, they are either retrieving or removing a resource that can typically be identified by an id in the URI.
History
- 16th August, 2021: First version