In this article, I am going to discuss Parameter Binding in ASP.NET Web API with Examples. Please read our previous article before proceeding to this article where we discussed creating custom method names in Web API applications. As part of this article, we are going to discuss the following pointers related to ASP.NET Web API Parameter Binding.
- What do you mean by Parameter Binding in Web API?
- Understanding the Default Parameter Binding in ASP.NET Web API.
- Understanding the Parameter Binding in ASP.NETÂ Web APIÂ with an Example.
- Understanding FromBody and FromUri attributes
- How to change the Default Parameter Binding Convention used by ASP.NET Web API Framework.
What do you mean by Parameter Binding in ASP.NET Web API?
The Parameter Binding in ASP.NET Web API means how the Web API Framework binds the incoming HTTP request data (query string or request body) to the parameters of an action method of a Web API controller.Â
The ASP.NET Web API action methods can take one or more parameters of different types. An action method parameters can be either of a complex type or primitive types. The Web API Framework binds the action method parameters either with the URLs query string or from the request body of the incoming HTTP Request based on the parameter type.
Default Parameter Binding in ASP.NET Web API
By default, if the parameter type is of the primitive type such as int, bool, double, string, GUID, DateTime, decimal, or any other type that can be converted from the string type then Web API Framework sets the action method parameter value from the query string. And if the action method parameter type is a complex type then Web API Framework tries to get the value from the body of the request and this is the default nature of Parameter Binding in Web API Framework. The following table lists the default rules for Web API Parameter Binding.
Note:Â The above diagram clearly shows that we do not have a request body for the GET and DELETE HTTP requests. So, in that case, it tries to get the data from the query string.
Understanding the Parameter Binding in ASP.NETÂ Web APIÂ with an Example.
We are going to use a testing tool called “Fiddler†to test these Verbs. Again we are going to use the following Employee table to understand the Parameter binding in Web API concepts.
Please use the following SQL Script which will create and populate the Employees database table along with the database with the required test data.Â
Creating a new ASP.NET Web API Project
Open Visual Studio and select File -> New –> Project as shown below
In the “New Projectâ€Â window, select “Visual C#â€Â under the “Installed – Templates†section. From the middle pane select the “ASP.NET Web Application†and then give a meaningful name to your application, here I provided the name as “EmployeeServiceâ€Â and then click on the “OK†button as shown in the below image
Once you click on the OK button a new dialog window will open with the Name “New ASP.NET Project†for selecting the Project Templates. From this window, you need to choose the WEB API project template and then click on the OK button as shown below.
At this point, you should have the Web API project created.
Adding ADO.NET Entity Data Model to retrieve data from the database
Right-click on the Models folder and then select Add -> New Item option which will open the Add New Item windows. From the “Add New Item†window select the “Data†from the left pane and then select the ADO.NET Entity Data Model from the middle pane of the Add New Item window.
In the name text box, provide a meaningful nake like EmployeeDataModel and click on the Add button as shown in the below image.
On the Entity Data Model Wizard, select the “EF Designer from database†option and click the Next button
From the Choose Your Data Connection screen, click on the “New Connection†button as shown below
Once you click on the New Connection Button it will open the Connection Properties window and from the “Connection Properties†window, set the following things
- Server Name = provide the server
- Authentication = Select the authentication type
- Select or enter a database name =Â WEBAPI_DB
- Click the OK button as shown below.
Once you click on the OK button it will navigate back to the Choose Your Data Connection wizard. Here Modify the Connection String as EmployeeDBContext and click on the Next Button as shown in the below image.
On the next screen, select Entity Framework 6.x as shown in the below image. This step may be optional if you are using a higher version of visual studio.
On Choose Your Database Objects and Settings screen, select the “Employees†table, provide the model namespace name and click on the Finish button as shown below.Â
Once you click on the Finish Button the edmx file will be generated.
Adding Web API Controller
Right-click on the Controllers folder and select Add -> Controller which will open a window to select the controller. From that window select “Web API 2 Controller – Empty†and then click on the “Add†button as shown below.
On the next screen set, the Controller Name as EmployeesController and click on the Add button as shown in the below image.
Copy and paste the following code into EmployeesController.
Depending on the value we specify for query string parameter gender, the Get() method should return the data.Â
/api/employees?gender=all Return All Employees
/api/employees?gender=Male Return All Male Employees
/api/employees?gender=Female Return All Female Employees
If the value for gender is not Male, Female, or All, then the service should return status code 400 Bad Request. For example, if we specify ABC as the value for gender, then the service should return status code 400 Bad Request with the following message.
Value for the gender must be Male, Female, or All. ABC is invalid.
Below is the modified Get() method
Gender is being passed as a parameter to the Get() method. The default value is “Allâ€. The default value makes the parameter optional. The gender parameter of the Get() method is mapped to the gender parameter sent in the query string
Understanding FromBody and FromUri attributes.
Let us understand their use with an example. Consider the following Put() method. This method updates the specified Employee details. Add the following PUT method within the Employees Controller
To update employee details whose Id is 1 we issue a Put request to the URIÂ /api/employees/1
Query string parameter names must match with the name of an action method parameter. However, they can be in a different order. If you are using Fiddler, the PUT request is as shown below. Notice the Id of the employee is in the URI and the employee data is in the request body.Â
At this point, if you execute the request, the employee data is updated as expected. Now lets include the Id as a query string parameter. In the first request, Id is specified as part of route data. Notice in Fiddler we have included the id parameter as a query string.Â
When we execute this request, the update succeeds as expected. When a PUT request is issued, Web API maps the data in the request to the PUT method parameters in the Employees Controller. This process is called Parameter Binding in ASP.NET Web API.
Default convention used by Web API for Parameter binding.
If the parameter is a simple type like int, bool, double, etc., the ASP.NET Web API Framework tries to get the value from the URI (Either from route data or from the Query String) whereas 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.
So in our case, the id parameter is a simple type, so Web API tries to get the value from the request URI. The employee parameter is a complex type, so Web API gets the value from the request body.Â
Note:Â Name of the complex type properties and query string parameters must match.
We can change this default behavior of the ASP.NET Web API Parameter Binding process by using [FromBody] and [FromUri] attributes. Notice in the example below, we have decorated the id parameter with the [FromBody] attribute which will force the Web API Framework to get it from the request body. We have also decorated the employee object with the [FromUri] attribute which will force the Web API Framework to get the employee data from the URI (i.e. Route data or Query String)
Here is the request from Fiddler
1. Employee data is specified in the URI using query string parametersÂ
2. The id is specified in the request body Â
 When we execute the request the update succeeds as expectedÂ
Are multiple FormBody attributes is allowed?
No, multiple FormBody is not allowed in a single action.Â