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.
- 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".
- Accept-Charset: Which character sets are acceptable like UTF-8 or ISO 8859-1.
- Accept-Encoding: Which content encodings are acceptable, such as gzip.
- 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 Architecture
Below picture describes how ASP.NET Web API routing Architecture. Routing is done
way depending on where it is hosted.
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 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
You can create custom message Handlers to include custom logic like authorization
or authentication or intercept http request.
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
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.
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.
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
- HttpServer: Gets request from host (IIS or Managed application).
- HttpRoutingDispatcher: Parse route information and depending on route dispatch
- 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
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
- URI Binding: The ModelParameterBinding object check URI for any custom IModelBinder
or IValueProvider and produces simple type.
- 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.
- 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
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
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
- HttpResponseMessage: HttpResoponseMessage is already prepared so no need
of any conversion, it directly pass to client through pipeline.
- Void: Action Method returns void and converts to HttpResponseMessage with
status code 204 (empty response).
- Media Type Formatter: The content negotiator plays role here to convert output
as expected by client.