Web API

Getting Started With ASP.NET Web API 2

  •  Create a project of type ASP.NET Web application and select the template type as Web API.Create Web API ProjectWeb API Template

 

  •  If you are just creating RESTful Services, only three folders are of use to us. Rest can be deleted.We need Controllers to receive and process the request and App_Start where we will define some of our configuration. The third is Models, which contains classes that define objects and the logic for interacting with the database or data items. The Model is used by request/response data and manipulated in controller.. Alternately, you can create a new Class project just to maintain the entities and another Data access project.

 

  • Define the routes in RouteConfig.cs within App_Start folder. Route defines the URL pattern and handler information. All the configured routes of an application stored in RouteTable and will be used by Routing engine to determine appropriate handler class or file for an incoming request. Every Web API must define atleast one route.RouteConfigWebAPI

 

  • As in the above figure, the route is configured using the MapRoute() method of RouteCollection, here name is “Default”, url pattern is “{controller}/{action}/{id}” and defaults parameter for controller, action method and id parameter.  Defaults defines which controller, action method or value of id parameter should be used if they do not exist in the incoming request URL. We can also define multiple routes. To understand more on the routing mechanism, go through ASP.NET MVC Routing .

 

  • In the WebApiConfig.cs, you can configure more settings for your Web API, e.g. Defining formatters, Custom Log Handlers, exception Filter Attributes.If you need xml and json support for your services, add this in Register function of WebApiConfig.

config.Formatters.Add(new XmlMediaTypeFormatter());
config.Formatters.Add(new JsonMediaTypeFormatter());

Now based on the Content-Type of request header, the corresponding data would be              returned

Web API Register XML_JSON

  • Create a new controller, Right click on Controller->Add->Controller. Select Web API 2 Controller – Empty. Create a controller action with Request and Response entities. In the below figure, we have GetClaimList as the action name, ClaimListResponse as the response entity and ClaimListRequest as the request entity. Here we are processing the request in a Helper class which validates the request paramters, calls the data access layer which inturn calls the  database with ADO.NET, fills the response entity and returns the object. We will not be getting into details of the Data access layer.

Web API Controller

To read the parameters from the request you can use either of the following :

Using a single parameter


// http://MyWebApiServices/v1/SingleParam?id=2
[Route("v1/SingleParam")]
[HttpGet]
public string TestAction1(int id)
{
return "test";
}

Using multiple parameters


//http://MyWebApiServices/v1/MultipleParam?id1=1&id2=2&id3=3
[Route("v1/MultipleParam")]
[HttpGet]
public string TestAction2(int id1, long id2, double id3)
{
return "test";
}

Using multiple parameters with Attribute Routing


// http://MyWebApiServices/v1/MultipleParam/2/3/4

[Route("v1/MultipleParam/{id1}/{id2}/{id3}")]
[HttpGet]
public string TestAction3(int id1, long id2, double id3)
{
return "test";
}

Using object in the URL


// http://MyWebApiServices/v1/ObjectParam?Id=1&Id2=2
[Route("v1/ObjectParam")]
[HttpGet]
public string GetUsingUri([FromUri] ClaimObject claimObject)
{
return "test:" + claimObject.Id1 + claimObject.Id2 ;
}

Using object in Request Body


[Route("v1/ObjectBodyParam")]
[HttpPost]
public string GetUsingBody([FromBody] ClaimObject claimObject)
{
return "test:" + claimObject.Id1+ claimObject.Id2 ;
}

  •  If you need the request paramter to decide whether to return xml or json (rather than request header as mentioned above), add these line of code to Register function of WebApiConfig. Now the Content-Type value of the query string will decide the formatter of the request. This will override the request header Content-Type.

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("Content-Type", "application/json", "application/json"));
GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("Content-Type", "application/xml", "application/xml"));

Web API Register XML_JSON With QueryString

  • Just hit the URI with specified paramters

 

I am migrating to Blogger for all my new blogs. You may visit https://helpmedevelop.blogspot.in/ for more insights.

Leave a comment