ASP.NET Web API, as we know now, is a framework that helps build Services over HTTP. Web API was introduced as a lightweight service framework keeping in mind the modern web development paradigm where multiple devices and client platforms access data via an API that’s made available over plain HTTP without the configuration overhead of WS-* type of Services. It does not impose client-side object proxy requirements and supports JSON and XML formats out-of-the-box for data transfer over the wire.
Today, we will look at the Lifecycle of an ASP.NET Web API message as it travels from the server to the client via the HttpRequest and back via the HttpResponse. We will also look at the various extensibility points in the pipeline. Once again thanks to Web API expert Sumit Maitra for all his valuable inputs.
The original flow chart was created by Microsoft and can be downloaded from here. The illustrations below are inspired by this original diagram.
The Web API Pipeline
The following image shows the major portions of the Web API Pipeline.
Hosting Web API
As we can see, Web API can be hosted either on ASP.NET or you could write a Console App or a Windows Service yourself to self-host it in a container of yours. So Web API’s flexibility starts right at the core as to where it can be hosted. This really opens things up for us as we go ahead.
a. ASP.NET Hosting: When hosted on ASP.NET, the lifecycle starts with the HttpControllerHandler which is an implementation of IHttpAsyncHandler and is responsible for passing requests into the HttpServer pipeline.
b. Self Hosting: When you are Self Hosting, the HttpServer pipeline starts at the HttpSelfHostServer which is an implementation of HttpServer and directly listens to HTTP requests.
HTTP Message Handlers
Once a request leaves your Service host, it travels as an HttpRequestMessage object in the pipeline. The next stage in the pipeline are the Message Handlers.
Delegating handlers are an extensibility point in the message pipeline allowing you to massage the Request before passing it on to the rest of the pipeline. The response message on its way back has to pass through the Delegating Handler as well, so any response can also be monitored/filtered/updated at this extensibility point.
Delegating Handlers if required, can bypass the rest of the pipeline too and send back and Http Response themselves.
If the request makes it through the option Delegation handlers, it reaches the Routing Dispatcher next. The dispatcher checks if the Route Handler is null. If it is null, it proceeds to the next step in the pipeline.
However if it’s not null, it implies there are one or more per-route message handlers in place and the request is passed on to the Handlers. Here it loops through the available handlers and picks the one matching the request, the request is then handled. Remember, you can have a delegation handler in your Route Handler, so you can bypass the rest of the pipeline even at this point.
If the routing handlers pass the request on to the next stage, the request enters the Controllers.
First step in the Controllers section of the pipeline is to check for and pass through the Authorization Filters. If there are Authorization Filters present and the request fails Authorization, the Auth filter truncates the request and sends back an Auth Failure response directly.
Once authorized successfully, the request proceeds into the Model Binding section. This is not a single step. In fact if we ‘Zoom in’ to the Model Binding ‘box’, we will see a process similar to the one below
A Zoomed in view of Model Binding
As we can see above, we start off with the three parts of HTTP Request, the URL, Header and Body. Each one is treated independently.
The URI goes through the ModelBinderParameterBinding object which checks further if there is custom IModelBinder or IValueProvider. The final outcome is a Simple Type.
The Entity Body is managed through the FormatterParameterBinding. We can plug in custom Media Type Formatters and if the request needs one of these two be utilized it is piped through the appropriate Media Type Formatter before it gets converted to the required Complext Type.
Http 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.
After Model Binding is complete, the pipeline proceeds to the Action Filters. Action filters are actually invoked twice, before and after the controller Action as shown by the ‘OnExecuting’ and ‘OnExecuted’ events.
The Action Invoker invokes the Controller Action using the binding and model state in the HttpActionContext. There is an extensibility point here also (not shown in the diagram). We can have a custom Implementation of IHttpActionInvoker if required.
The Action Invoker finally invokes the Controller action and the return journey of the Message in form of HttpResponseMessage begins from here. In case there is an exception while invoking the Action, the exception is routed to the Exception Filters which can send back appropriate Error Response.
The controller action executes the code in the Action method and returns from the Action Method. Depending on what it returns, the Result Conversion piece kicks in and prepares the HttpResponseMessage.
We have the following ‘Zoomed in’ view of how the Response Message is prepared.
A Zoomed In view of Result Conversion into HttpResponseMessage
The outcome of the Action method can be of three types
a. An HttpResponseMessage – In this case, there is nothing to convert and the message is directly passed through and is on its way back in the pipeline.
b. A void – If the outcome of the Action Method is a void, it is actually converted into an HttpResponseMessage with status 204 implying – No Content.
c. If any other Types are returned by the Action method, Content Negotiation and Media Type Formatters kick in. The content negotiator checks to see if we can return the requested content, picks up the appropriate Media Type Formatter, churns the return data through it, to get an appropriate HttpResponseMessage out. As we can see, both the Content Negotiator and the MediaTypeFormatter are green, implying they are extensibility points and that they can be plugged in with custom implementations.
Once we have the required HttpResponseMessage, it begins its journey back through the components of the pipeline it traversed originally.
That wraps up our trip down an Http Message’s lifecycle through the ASP.NET Web API pipeline. As we saw it is a very flexible pipeline with all major components being extensible as an additional plugin or in form of a custom replacement.
Hopefully this has given you a fair idea of how a Web API works and you can now write your code to maximize its potential.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce the The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this eBook aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on .NET Standard and the upcoming C# 8.0 too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Purchase this eBook at a Discounted Price!