Saturday, March 24, 2018

FromBody and FromUri attributes in ASP.Net WebAPI

FromBody and FromUri attributes:

Take a look at the Put method we have defined already.
While executing this method from Fiddler, we pass the id parameter from the request uri and the employee parameter from request body.
When a request is issued, the data that we have in a request needs to be mapped to the parameters of the Put method in a controller. We can also pass the id parameter using query string by simply placing a question mark followed by name of the parameter, just like we do in plain ASP.Net.
Now let’s understand what Parameter Binding is. By default ASP .Net web API default parameter binding convention is:
  • If the parameter is of simple type like int, Boolean, double, etc., Web API tries to get the value from uri. (either from route data or querystring).
  • If the parameter is of complex type like Employee, Customer, Product, etc, Web API tries to get the value from the request body.
We can change this default convention by using FromBody and FromUri attributes.
public HttpResponseMessage Put([FromBody]int id, [FromUri]Employee employee)
  • Use [FromBody] attribute to force Web API to get simple types from request body.
  • Use [FromUri] attribute to force Web API to get the complex types from request uri i.e. from route data or querystring.

Look at the below image. We have specified the values for complex type Employee in the request uri.
Note that the name of the parameters should be same as that of the properties defined for the complex type. Here the parameters FirstName, LastName, Gender, Salary are same as that of the properties of the Employee type.
In the below images, we are forcing Web API to look for id parameter in the request body.








No comments:

Post a Comment