Getting started with ASP.NET Web API

This article helps you to understand ASP.NET Web API concepts

This article explains below concepts on ASP.NET Web API

  1. Content Negotiation in Web API
  2. ASP.NET Web API Architecture
  3. ASP.NET Web API Message Life Cycle
  4. ASP.NET Web API Hosting
  5. ASP.NET Web API Message Handler
  6. ASP.NET Web API Controllers, Authorization Filters, Model Bindings
  7. ASP.NET Web API Action Filters, Action Invoker, Controller Action

Introduction to ASP.NET Web API

ASP.NET Web API is Microsoft framework to build services which can communicate with HTTP / HTTPS protocols. Web API request / response are simple, light weight as compare to other service types. Any client like browsers, mobile, tablet, hand held devices can communicate to ASP.NET Web API provided they are able to handle http requests and response. Clients can make GET, POST, PUT, DELETE requests to Web API.

Web API deals with Accept headers of request and returns response accordingly in JSON, XML or any other requested format.


What is content Negotiation in Web API

In ASP.NET Web API, clients can request data in specific media type like JSON or XML. The definition of content negotiation is the process of selecting the best representation for a given response when there are multiple representations available.

The content negotiation is done accordingly below request headers.

  1. Accept: The media type requested by clients and acceptable for response like “application/json,” “application/xml,” or a custom media type such as "application/vnd.example+xml".
  2. Accept-Charset: Which character sets are acceptable like UTF-8 or ISO 8859-1.
  3. Accept-Encoding: Which content encodings are acceptable, such as gzip.
  4. Accept-Language: The preferred language, such as “en-us”, "mr-IN".

At this time, there is no built-in support for Accept-Encoding or Accept-Language.
Below picture describes how content negotiation works.

asp net web api content negotiation


ASP.NET Web API Architecture

Below picture describes how ASP.NET Web API routing Architecture. Routing is done in different way depending on where it is hosted.

asp.net web api routing architecture

You can host your Web API in IIS or managed application like Windows Service or Console application. When you host in IIS ASP.NET Pipeline and ASP.NET routing works with ApiController whereas when you host in managed application WCF self host works with ApiController to handle requests.

Routing in ASP.NET Web API architecture works in three different steps.
1. Find matching route and parse route data.
2. Find matching controller.
3. Find matching action.

If any step fail to find matching route, execution will be aborted. Web API uses HTTPRouteCollection and Route tables to hold routing information.


ASP.NET Web API Message Life Cycle

Service Host sends Web API request to HttpRequestMessage object in pipeline.

HttpRequestMessage handles request with Delegating Handler and Routing Dispatcher.


Delegating Handler

Delegating Handlers are used in Web API to represent message handlers before routing. They are sequentially arranged modules in HTTP pipeline, each one receives requests, does some work and pass on to next modules. While returning response it has to pass through the Delegating Handler as well, so any response can also be monitored/filtered/updated at delegating handler.

If required Delegating Handlers can skip rest of the pipeline and send response back themselves.

You can create custom message Handlers to include custom logic like authorization or authentication or intercept http request.


Routing Dispatcher

After Delegating Handler request reaches to Routing Dispatcher. The Routing Dispatcher implements HttpRoutingDispatcher class. It obtains the routing data (if hosted in IIs) from request or performs the route resolution (if hosted in managed applications). If no match found it returns response message with 404 status code.

It uses the route data to choose next handler to forward request depending on matched IHttpRoute.


ASP.NET Web API Hosting

As mentioned earlier, ASP.NET Web API can be hosted in IIS or you can write console application or windows service to host Web APIs.


ASP.NET Hosting:

When you host your ASP.NET Web API in IIS, the request life cycle starts at HttpControllerHandler which implements IHttpAsyncHandler. HttpControllerHandler responsible for process request and pass it to next HttpServer pipeline. See more details about how to host ASP.NET Web API in IIS.


Self Hosting:

When you host your ASP.NET Web API in managed application, the request life cycle starts at HttpSelfHostServer means it directly listens HTTP requests. HttpSelfHostServer implements HttpServer class.


ASP.NET Web API Message Handler

Message handlers implements abstract HttpMessageHandler class. It receives an HTTP request and returns an HTTP response. Request and response travels through chained message handlers.

ASP.Net Web API uses below built in message handlers

  1. HttpServer: Gets request from host (IIS or Managed application).
  2. HttpRoutingDispatcher: Parse route information and depending on route dispatch request.
  3. HttpControllerDispatcher: Sends request to corresponding Web ApiController.

You can create custom handlers by using System.Net.Http.DelegatingHandler. This custom handler can be used for read or modify request headers, validate request before controller, add authorization or authentication features, add response headers to response.


ASP.NET Web API Controllers, Authorization Filters, Model Bindings

ApiControllers: ApiControllers implements IHttpController interface. You can implement ApiController in ASP.NET Web form or ASP.NET MVC application. You can see how to create ASP.NET Web API in MVC application. The Web ApiController and MVC controller works in similar way however they have some difference like Web API allows Content negotiation, Flexibility, Separation of concerns.
The Routing handler pass request to next stage and it comes to controllers.

Authorization Filters: When request comes to controllers, the first step is to check and pass Authorization Filters. If Authorization fails, Authorization Filters truncate request and sends back Authorization failure response with out executing code from action methods. Get more details about ASP.NET MVC filters.
You can create custom Authorization Filters by deriving AuthorizationFilterAttribute class from System.Web.Http.Filters namespace. AuthorizationFilterAttribute will give you access to HttpActionContext, AuthenticationHeaderValue and other request parameter which helps you to implement custom authorization.


Model Binding: Once the request pass through Authorization Filters, request proceeds to Model Bindings. The Model Binding infrastructure in ASP.NET Web API provides necessary runtime services for

  1. URI Binding: The ModelParameterBinding object check URI for any custom IModelBinder or IValueProvider and produces simple type.
  2. Formatter Binding: ASP.NET Web API returns dynamic output like JSON or XML as required by request headers. FormatterParameterBinding can plug in custom Media Type Formatters and produce custom output.
  3. Parameter Binding: If we have a custom HttpParameter binding module the entire request is piped through it instead and the final output could be any type spit out by the custom Http Parameter Binder.

ASP.NET Web API Action Filters, Action Invoker, Controller Action

Action Filters: After model binding pipeline proceeds to action filters. Action Filters get processed twice on OnExecuting and OnExecuted events. Action Filters are included in System.Web.Http.Filters namespace. You can create your custom Action Filters by using this namespace and deriving ActionFilterAttribute class.

Action Invoker: The Action Invoker invokes the Controller Action using the binding and model state in the HttpActionContext. We can have a custom Implementation of IHttpActionInvoker by using System.Web.Http.Controllers namespace.
The Action Invoker finally invokes the Controller action and give reply of the Message as HttpResponseMessage. If there is an exception while invoking the Action, the exception is routed to the Exception Filters which send back appropriate Error Response to client.

Controller Action: The controller action is responsible for execution of code in Action method and returns from the Action Method. Depending on what Action Method returns, the HttpResponseMessage get prepared and return to client.
Action Method return as

  1. HttpResponseMessage: HttpResoponseMessage is already prepared so no need of any conversion, it directly pass to client through pipeline.
  2. Void: Action Method returns void and converts to HttpResponseMessage with status code 204 (empty response).
  3. Media Type Formatter: The content negotiator plays role here to convert output as expected by client.

Speak your mind :
Leave a comment for this article on dotnetbloogers.com
User profile picture on dotnetmentors.com

by Anil at 8/24/2015 2:03:00 AM
Its very useful. Thanks.
post comment on dotnetmentors.com