Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

ASP.NET Web API Parameter vs Model Binding

4.79/5 (6 votes)
16 Aug 2021CPOL1 min read 9.8K  
The differences between parameter and model binding with ASP.NET WebAPI
ASP.NET provides the ability to send values to a method on a controller. This is called binding. The two main types of binding are parameter and model. This article is a quick review on using both types of binding.

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:

C#
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.

C#
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.

Image 1

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)