What is parameter binding in C# ASP.NET WebAPI?

CsharpServer Side ProgrammingProgramming

Binding is a process to set values for the parameters when Web API calls a controller action method.

Web API methods with the different types of the parameters and how to customize the binding process.

If the parameter is a simple type like int, bool, double, etc., Web API tries to get the value from the URI (Either from route data or from the Query String)

if the parameter is a complex type like Customer, Employee, etc., then the Web API Framework tries to get the value from the request body.

We can change this default behavior of the parameter binding process by using [FromBody] and [FromUri] attributes.


If the parameter is of simple type, then web Api tries to get the value from the URI

.NET Primitive type like double,DateTime,GUID string any type which can e converted from the String type


public Student Get(int id){}


If the parameter of type Complex type, then Web Api will try to bind the values from the message body.


Public Student Post(Employee employee){}


To force Web API to read a complex type from the URI, add the [FromUri] attribute to the parameter

Use [FromUri] attribute to force Web Api to get the value of Complex type from QueryString.


public Student Get([FromUri] Employee employee)
public HttpResponseMessage Get([FromUri] Employee employee) { ... }


Use [FromBody] attribute to get the value of Primitive type from the request body, opposite to the default values

No, multiple FormBody is not allowed in a single action.

To force Web API to read a simple type from the request body, add the [FromBody]

In this example, Web API will use a media-type formatter to read the value of name from the request body


public Student Post([FromBody] string name]){...}
public HttpResponseMessage Post([FromBody] string name) { ... }
Published on 19-Aug-2020 17:50:58