Inject Multiple Arguments To A Web API Method

There can be various scenarios when you may have to pass multiple arguments in a Web API get method. Though there might be a few more ways, I have used the default configuration mapping which I am sharing here in this article.

We should pass arguments as additional parameters. It is especially easy with GET requests. This will work in Web API 1 & 2:

Here, I have a simple controller Employee which has the following Action Method defined below and performs a set of statements such as fetch a record from collection. GetEmployeeByID method takes two parameters as arguments.

  1. [ActionName("GetEmployeeByID")]    
  2. public class EmployeesController: ApiController    
  3. {    
  4.     public Employee Get(int ? id = null, string userName = null)    
  5.     {    
  6.         return listEmp.First(e => e.ID == id);    
  7.     }    
  8. }  
For this purpose, I have the following routing which is placed in WebApiConfig.cs as shown below in depicted image,

code
  1. public static void Register(System.Web.Http.HttpConfigurationconfig)     
  2. {    
  3.     config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new     
  4.      {    
  5.         id = RouteParameter.Optional    
  6.     });    
  7. }  
I run my application and verify whether API is up or not. Kindly find the given below image to identify this.

asp.net

It shows the API is running and ready to perform some action. Along with this I have Postman running on the side where I paste the specific url which meets the requirement as shown below,

postman

As soon as I click on the Send button it will go to the respective controller’s action to executea  set of statements. The image depicted below shows that username argument has the value “Sachin Kalia”. In the same way, you can utilize such value at action level.

code

The output will be like given image shown below,

output

Note: Suppose you would like to get output in XML form instead of JSON, You just need to add header value in a request.

A simple example to receive output in a different form: Click on Headers button on the right side of Postman client screen. The following window will appear as shown below and fill the required details like Accept: Application/xml in headers part.

postman

As soon as the user clicks on send button it should respond to the request in XML form as shown in below image.

postman

This is the sample code segment which fetches records from database and responds in WebAPi response form as shown below,
  1. [HttpGet]    
  2. // [Route("api/{employees}/{id}/{userName}")]    
  3. [ActionName("GetEmployeeByID")]    
  4. publicEmployee Get(int id, stringuserName)    
  5. {    
  6.     returnlistEmp.First(e => e.ID == id);    
  7.     SqlDataReader reader = null;    
  8.     SqlConnectionmyConnection = newSqlConnection();    
  9.     myConnection.ConnectionString = @ "Server=.;Database=DBCompany;User ID=sa;Password=Tpg@1234;";    
  10.     SqlCommandsqlCmd = newSqlCommand();    
  11.     sqlCmd.CommandType = CommandType.Text;    
  12.     sqlCmd.CommandText = "Select * from tblEmployee where EmployeeId=" + id + "";    
  13.     sqlCmd.Connection = myConnection;    
  14.     myConnection.Open();    
  15.     reader = sqlCmd.ExecuteReader();    
  16.     Employeeemp = null;    
  17.     while (reader.Read())    
  18.     {    
  19.         emp = newEmployee();    
  20.         emp.EmployeeId = Convert.ToInt32(reader.GetValue(0));    
  21.         emp.Name = reader.GetValue(1).ToString();    
  22.         emp.ManagerId = Convert.ToInt32(reader.GetValue(2));    
  23.     }    
  24.     returnemp;    
  25.     myConnection.Close();    
  26. }    
This is one of the possible ways of doing this. In the next article we can achieve the same thing in a more linear fashion using Route Attribute.
 
Read more articles on Web API:


Similar Articles