Getting started with ASP.NET Web API

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 a Microsoft framework to build services that can communicate with HTTP / HTTPS protocols. Web API request / response is simple, lightweight as compare to other service types. Any client like browsers, mobile, tablet, handheld 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 the 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 types 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 a 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.
The below picture describes how content negotiation works.

asp net web api content negotiation

ASP.NET Web API Architecture

The below picture describes how ASP.NET Web API routing Architecture. Routing is done in a different way depending on where it is hosted. web api routing architecture

You can host your Web API in IIS or managed applications 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 selfhost works with ApiController to handle requests.

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

If any step fails to find a 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 a Web API request to the HttpRequestMessage object in the pipeline.

HttpRequestMessage handle 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 the HTTP pipeline, each one receives requests, does some work, and passes on to the 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 the 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's request reaches to Routing Dispatcher. The Routing Dispatcher implements the HttpRoutingDispatcher class. It obtains the routing data (if hosted in IIS) from the requestor 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 the next handler to forward requests 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 a managed application, the request life cycle starts at HttpSelfHostServer means it directly listens to HTTP requests HttpSelfHostServer implements HttpServer class.

ASP.NET Web API Message Handler

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

ASP.Net Web API uses below built in message handlers

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

You can create custom handlers by using System.Net.Http.DelegatingHandler. This custom handler can be used to read or modify request headers, validate request before controller, add authorization or authentication features, add response headers to the 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 CRUD Operation. The Web ApiController and MVC controller works in a similar way however they have some differences like Web API allows Content negotiation, Flexibility, Separation of concerns.
The Routing handler passes the request to the next stage and it comes to controllers.

Authorization Filters: When a 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 without 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 parameters 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 checks for any custom IModelBinder or IValueProvider and produces a 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
Please login to post your comment!

  • geeksarray user
    08/24/2015 02:03 AM Anil

    Its very useful. Thanks.