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 Handler

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.

Routing Dispatcher

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.

Controllers

If the routing handlers pass the request on to the next stage, the request enters the Controllers.

Authorization Filters

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.

Model Binding

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.

URI Binding

The URI goes through the ModelBinderParameterBinding object which checks further if there is custom IModelBinder or IValueProvider. The final outcome is a Simple Type.

Formatter Binding

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.

Action Filters

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.

Action Invoker

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.

Controller Action

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.

Result Conversion

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.

Wrap Up

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.

Lifecycle of an ASP.NET Web API Message的更多相关文章

  1. ASP.NET WEB API处理流程

    前言:大图请看 http://www.asp.net/posters/web-api/ASP.NET-Web-API-Poster.pdf Web Api Hosting 我们不仅可以通过Web应用程 ...

  2. Custom Exception in ASP.NET Web API 2 with Custom HttpResponse Message

    A benefit of using ASP.NET Web API is that it can be consumed by any client with the capability of m ...

  3. ASP.NET Web API与Owin OAuth:使用Access Toke调用受保护的API

    在前一篇博文中,我们使用OAuth的Client Credential Grant授权方式,在服务端通过CNBlogsAuthorizationServerProvider(Authorization ...

  4. 8 种提升 ASP.NET Web API 性能的方法

    ASP.NET Web API 是非常棒的技术.编写 Web API 十分容易,以致于很多开发者没有在应用程序结构设计上花时间来获得很好的执行性能. 在本文中,我将介绍8项提高 ASP.NET Web ...

  5. 推荐升级ASP.NET Web API 2

    ASP.NET Web API 使用很长时间了,期间也碰到不少问题,升级到WebAPI2后这些问题都解决了,稳定性方面也提升不少,所以推荐使用.碰到的问题是下面的2类: 1.multipart/for ...

  6. Self Host模式下的ASP. NET Web API是如何进行请求的监听与处理的?

    构成ASP.NET Web API核心框架的消息处理管道既不关心请求消息来源于何处,也不需要考虑响应消息归于何方.当我们采用Web Host模式将一个ASP.NET应用作为目标Web API的宿主时, ...

  7. ASP.NET Web API中的Controller

    虽然通过Visual Studio向导在ASP.NET Web API项目中创建的 Controller类型默认派生与抽象类型ApiController,但是ASP.NET Web API框架本身只要 ...

  8. 总体介绍ASP.NET Web API下Controller的激活与释放流程

    通过<ASP.NET Web API的Controller是如何被创建的?>我们已经对HttpController激活系统的核心对象有了深刻的了解,这些对象包括用于解析程序集和有效Http ...

  9. 在ASP.NET Web API项目中使用Hangfire实现后台任务处理

    当前项目中有这样一个需求:由前端用户的一个操作,需要触发到不同设备的消息推送.由于推送这个具体功能,我们采用了第三方的服务.而这个服务调用有时候可能会有延时,为此,我们希望将消息推送与用户前端操作实现 ...

随机推荐

  1. redis高可用 - redis集群

    redis-sentinel方案提供了单点的高可用解决方案,但是当数据量和业务量极速增长时,单点的reids不可能无限的纵向扩容(增大内存),这个时候就需要redis有集群的能力来扛. redis集群 ...

  2. 这是一份很详细的 Retrofit 2.0 使用教程(含实例讲解)

    前言 在Andrroid开发中,网络请求十分常用 而在Android网络请求库中,Retrofit是当下最热的一个网络请求库 今天,我将献上一份非常详细Retrofit v2.0的使用教程,希望你们会 ...

  3. 网络TCP建立连接为什么需要三次握手而结束要四次

    忽然顿悟了,不管三次握手,还是四次握手,这是保证信息来回两个链路可达(也就是信息能从A到B,也能从B到A)的最低要求.-2018-9-17-晚上九点 举个打电话的例子: A : 你好我是A,你听得到我 ...

  4. Mongo Plugin插件(编辑器PyCharm的Mongo插件安装与使用)

    博主接触到MongoDB数据库.用普通的Navicat工具 是不支持的 正准备重新安装一款对应的可视化工具.刚好发现在PyCharm编辑中有连接mongoDB数据的插件 Mongo Plugin 这里 ...

  5. BooStrap4文档摘录: 1. Layout

    文档:  https://getbootstrap.com/docs/4.1/layout/overview/ w3c的案例:很直观: https://www.w3schools.com/bootst ...

  6. bzoj1058: [ZJOI2007]报表统计 stl xjbg

    小Q的妈妈是一个出纳,经常需要做一些统计报表的工作.今天是妈妈的生日,小Q希望可以帮妈妈分担一些工作,作为她的生日礼物之一.经过仔细观察,小Q发现统计一张报表实际上是维护一个可能为负数的整数数列,并且 ...

  7. HDU1754 I hate it_线段树(入门级别)

    I Hate It Time Limit: 9000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total S ...

  8. mysql-connect-odbc连接

  9. (C#基础)深浅拷贝理解

    一方面感觉实在无趣,不知道做什么了,纯粹来个打字练习,于是有了这个. 二方面深感自己C#基础之薄弱,于是对着园友的文章一边看,一边练习,因为很多次看了,没有多久就忘了,还有练习过程中会出现一些问题,这 ...

  10. springmvc的表单标签

    1. Spring提供的轻量级标签库 2.可在JSP页面中渲染HTML元素的标签 3 用法 1)必须在JSP页面的开头处声明taglib指令 <%@ taglib prefix="fm ...