Loading

ASP.NET Web API

How to implement parameter Binding in Web API?. The Complete ASP.NET Web API Developer Course 2023 [Videos].

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.

  1. What do you mean by Parameter Binding in Web API?
  2. Understanding the Default Parameter Binding in ASP.NET Web API.
  3. Understanding the Parameter Binding in ASP.NET Web API with an Example.
  4. Understanding FromBody and FromUri attributes
  5. 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.

Default Parameter Binding in Web API

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.

Web API Parameter Binding

Please use the following SQL Script which will create and populate the Employees database table along with the database with the required test data. 

CREATE DATABASE WEBAPI_DB
GO
USE WEBAPI_DB
GO
CREATE TABLE Employees
(
ID int primary key identity,
FirstName nvarchar(50),
LastName nvarchar(50),
Gender nvarchar(50),
Salary int
)
GO









GO
Creating a new ASP.NET Web API Project

Open Visual Studio and select File -> New –> Project as shown below

Parameter Binding in ASP.NET Web API

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

Web API Parameter Binding

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.

Web API Parameter Binding

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.

Web API Parameter Binding

On the Entity Data Model Wizard, select the “EF Designer from database” option and click the Next button

Web API Parameter Binding

From the Choose Your Data Connection screen, click on the “New Connection” button as shown below

Parameter Bindings in WEB API

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

  1. Server Name = provide the server
  2. Authentication = Select the authentication type
  3. Select or enter a database name = WEBAPI_DB
  4. Click the OK button as shown below.

Parameter Bindings in WEB API

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.

Parameter Bindings in WEB API

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.

Web API Parameter Binding

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. 

Web API Parameter Binding

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.

Parameter Binding in ASP.NET Web API

On the next screen set, the Controller Name as EmployeesController and click on the Add button as shown in the below image.

Parameter Bindings in WEB API

Copy and paste the following code into EmployeesController.

public class EmployeesController : ApiController
{
public HttpResponseMessage GET()
{
using (EmployeeDBContext dbContext = new EmployeeDBContext())
{
var Employees = dbContext.Employees.ToList();
return Request.CreateResponse(HttpStatusCode.OK, Employees);
}
}
}

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

public class EmployeesController : ApiController
{
public HttpResponseMessage Get(string gender = "All")
{
using (EmployeeDBContext dbContext = new EmployeeDBContext())
{
switch (gender.ToLower())
{
case "all":
return Request.CreateResponse(HttpStatusCode.OK,
dbContext.Employees.ToList());
case "male":
return Request.CreateResponse(HttpStatusCode.OK,
dbContext.Employees.Where(e => e.Gender.ToLower() == "male").ToList());
case "female":
return Request.CreateResponse(HttpStatusCode.OK,
dbContext.Employees.Where(e => e.Gender.ToLower() == "female").ToList());
default:
return Request.CreateErrorResponse(HttpStatusCode.BadRequest,
"Value for gender must be Male, Female or All. " + gender + " is invalid.");
}
}
}
}
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

public HttpResponseMessage Put(int id, Employee employee)
{
try
{
using (EmployeeDBContext dbContext = new EmployeeDBContext())
{
var entity = dbContext.Employees.FirstOrDefault(e => e.ID == id);
if (entity == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound,
"Employee with Id " + id.ToString() + " not found to update");
}
else
{
entity.FirstName = employee.FirstName;
entity.LastName = employee.LastName;
entity.Gender = employee.Gender;
entity.Salary = employee.Salary;
dbContext.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, entity);
}
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}

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. 

Parameter Binding in ASP.NET Web API

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. 

Parameter Binding in Web API

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)

public HttpResponseMessage Put([FromBody]int id, [FromUri]Employee employee)
{
try
{
using (EmployeeDBContext dbContext = new EmployeeDBContext())
{
var entity = dbContext.Employees.FirstOrDefault(e => e.ID == id);
if (entity == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound,
"Employee with Id " + id.ToString() + " not found to update");
}
else
{
entity.FirstName = employee.FirstName;
entity.LastName = employee.LastName;
entity.Gender = employee.Gender;
entity.Salary = employee.Salary;
dbContext.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, entity);
}
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
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  

Parameter Binding in Web API 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. 

See All

Comments (319 Comments)

Submit Your Comment

See All Posts

Related Posts

ASP.NET Web API / Blog

What is ASP.NET Web API Application?

In this ASP.NET Web API Tutorials series, I covered all the features of ASP.NET Web API. You will learn from basic to advance level features of ASP.NET Web API. The term API stands for “Application Programming Interface” and ASP.NET Web API is a framework provided by Microsoft which makes it easy to build Web APIs, i.e. it is used to develop HTTP-based web services on the top of .NET Framework.
3-Feb-2022 /34 /319

ASP.NET Web API / Blog

How to creat ASP.NET Web API Application using Visual Studio?

In this article, I am going to discuss the step-by-step procedure for Creating ASP.NET Web API Application. Please read our previous article before proceeding to this article where we gave an overview of the ASP.NET Web API framework. As part of this article, we ate going to discuss the following pointers.
3-Feb-2022 /34 /319

ASP.NET Web API / Blog

How to add Swagger in Web API Application?

In this article, I am going to discuss how to add Swagger in Web API Application to document and test restful Web API services. Please read our previous article where we discussed How to Create an ASP.NET Web API Application step by step before proceeding to this article as we are going to work with the same example. As part of this article, we are going to discuss the following pointers.
3-Feb-2022 /34 /319