Wednesday, April 3, 2019

Optional parameters in ASP.NET Web API

In this blog we discuss about optional parameters in WEB API URL and there are many way to pass parameters in Web API

·           Header
·           Query String
·           Path
·           HTTP Request Body 

Header Parameter – In  Web API design, mostly time header parameter is used to pass sensitive data like user id, password, and token etc. in http request header for authorization

Path Parameter – Path parameter is required part of WEB API URL, which is not optional


In ASP.NET Web API, the optional parameter is allowed in route

1
2
3
4
5
6
[HttpGet]
[Route("api/resources/{id:int}/{includedetail:bool=false}")]       
public IHttpActionResult GetResource(int id, bool includedetail)
{
 return Ok(_engine.GetResourceByID(id, includedetail));
}

In above method, if includedetail parameter is not available, it takes default value of parameter.


this URL does not contain includemessage parameter and route will invoke above method with default value of includeddetail parameter


this URL does contain includemessage parameter and route will invoke above method with pass value for includedetail parameter.

Query String:  query string parameter appear in API URL after ‘&’ and we can use it for optional parameter.


URL:  https://CodePoints/API/resources/1000?includedetail=true

this url have the includeddetail as query string and route will invoke the below API action with provided value for includeddetail.


this url doent have the includeddetail as query string and route will invoke the below API action and in api method, the includedetail parameter is optional parameter, if route does not provide its value, it will take default value (false).

1
2
3
4
5
6
[HttpGet]
[Route("api/resources/{id:int}")]       
public IHttpActionResult GetResource(int id, bool includedetail = false)
{
 return Ok(_engine.GeResourceByID(id, includedetail));
}

Request Body:  when request is posted, it sends the json object in request body and mostly it is pair of key /value

1
2
3
4
{
“resourseid” : 0,
“resourcedescription” : “Simple”
}

No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...