FormBody And FormURI In WebAPI

Overview

In this article, we will see how to use formBody and formURI in ASP.NET WebAPI. So, let’s start. We will be using the same example here.



We have used this PUT Verb to update an employee in employee details. Let’s request a PUT request from fiddler.



So, here in fiddler, we are issuing a request which we want to update data to. Here, we are passing the id as 1. We want to update the employee details whose id is 1. Now, let’s execute the request and check details in table.



The records here are updated successfully.

At the moment the Id in the URI which we want to update is the part of the route data. Now let’s use a querystring parameter to specify the Id instead. Now go back to fiddler and change the parameter to querystring.



As you can see, we have specified a parameter here and we are passing the same Id. Now, let’s execute that request and let’s see in our Database table.



The corresponding values got updated here. Now, the data we have in fiddler needs to be mapped to the PUT method in our EmployeesController.

WebAPI default Convention for Binding parameters

  • If the parameter is a simple type like int, bool, double etc., WebAPI tries to get values from the URI (Either from route data or from QueryString).
  • If a parameter is a complex type like customer, product, employee etc., WebAPI tries to get values from request body.

To change the default parameter binding process use [FormBody] and [FormUri] attributes. Here, the id with an integer type is declared as [FormBody] attribute.

Here in this example, WebAPI is going to look for the request in the value parameter and also in the body parameter and process the request accordingly.



Now here kindly use FromUri attribute and lets process a request from fiddler with the help of Querystring



Now, issue a request in the URI as above and execute the request and check whether it is successfully updated or not:



As you can see, the values which we have specified in the URI got updated successfully. At the moment, WebAPI is looking for data for the parameters which we have specified in our PUT method.



Now, we want to read the data from corresponding ID. We are using formBody attribute here. Build your solution and go to fiddler. In that, specify ID in request body.



Notice we are passing ID parameter in the URI, which we don’t need because we are specifying id in the request body. So, remove the ID value from the URI and execute the request. Once you execute the request, check the updated values in employees table .


Similar Articles