目录

  1. HttpMessageHandler

  2. Web Host模式处理过程

  3. Self Host模式处理过程

HttpMessageHandler

Web API处理管道由一系列HttpMessageHandler组成

public abstract class HttpMessageHandler : IDisposable
{
protected internal abstract Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken); protected virtual void Dispose(bool disposing) public void Dispose()
}

而一般在管道中,我们使用DelegatingHandler

public abstract class DelegatingHandler : HttpMessageHandler
{
public HttpMessageHandler InnerHandler { get; set; }
protected internal override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return this.innerHandler.SendAsync(request, cancellationToken);
}
}

头部是HttpServer

public class HttpServer : DelegatingHandler
{
public HttpMessageHandler Dispatcher { get; }
public HttpConfiguration Configuration { get; }
protected virtual void Initialize()
{
this.InnerHandler = HttpClientFactory.CreatePipeline(this._dispatcher, (IEnumerable<DelegatingHandler>) this._configuration.MessageHandlers);
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
this.EnsureInitialized();
return await base.SendAsync(request, cancellationToken);
}
}

其中Dispatcher就是管道的尾部

默认为HttpRoutingDispatcher

public class HttpRoutingDispatcher : HttpMessageHandler
{
public HttpConfiguration Configuration { get; }
private readonly HttpMessageInvoker _defaultInvoker = new HttpControllerDispatcher(configuration); public HttpRoutingDispatcher(HttpConfiguration configuration, HttpMessageHandler defaultHandler) protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
//1. Routing
IHttpRouteData routeData = request.GetRouteData();
if (routeData == null)
{
routeData = this._configuration.Routes.GetRouteData(request);
if (routeData != null)
request.SetRouteData(routeData);
}
//2. Dispatcher
this._defaultInvoker.SendAsync(request, cancellationToken);
}
}

实现Dispatcher(选择IHttpController)的对象默认为HttpControllerDispatcher

public class HttpControllerDispatcher : HttpMessageHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpControllerDescriptor controllerDescriptor = this.ControllerSelector.SelectController(request);
IHttpController controller = controllerDescriptor.CreateController(request);
return await controller.ExecuteAsync(controllerContext, cancellationToken);
}
}

验证管道

public class DemoController : ApiController
{
public IEnumerable<string> Get()
{
var cfg = new HttpConfiguration();
cfg.MessageHandlers.Add(new Handler1());
cfg.MessageHandlers.Add(new Handler1());
cfg.MessageHandlers.Add(new Handler1());
var server = new MyServer(cfg);
server.Initialize();//生成HttpMessageHandler链
return GetHandlers(server);
} private IEnumerable<string> GetHandlers(MyServer server)
{
DelegatingHandler next = server;
yield return next.ToString();
while (next.InnerHandler != null)
{
yield return next.InnerHandler.ToString();
next = next.InnerHandler as DelegatingHandler;
if (next == null)
break;
}
}
}
class MyServer : HttpServer
{
public MyServer(HttpConfiguration cfg) : base(cfg) { } public new void Initialize()//暴露Initialize方法
{
base.Initialize();
}
}
class Handler1 : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
}

浏览器中请求:

Web Host模式处理过程

上节我们说到HttpControllerHandler为Web Host下的处理程序.

public class HttpControllerHandler : HttpTaskAsyncHandler
{
private readonly HttpMessageInvoker _server = GlobalConfiguration.DefaultServer; public override Task ProcessRequestAsync(HttpContext context)
{
response = await this._server.SendAsync(request, cancellationToken);
await response.Content.CopyToAsync(context.Response.OutputStream);
}
}

从上面的代码中我们看到

  1. HttpControllerHandler实现的是异步HttpControllerHandler接口

  2. 在ProcessRequestAsync方法中 通过GlobalConfiguration.DefaultServer 启动了WebAPI管道

Self Host模式处理过程

Self Host目前可以说分为2种

  1. OWIN
  2. HttpBinding

本节重点说明一下传统方式的HttpBinding,WebAPI使用的Message为HttpMessage

通过Nuget可以非常方便的操作

Install-Package Microsoft.AspNet.WebApi.SelfHost

using (var server = new HttpSelfHostServer(new HttpSelfHostConfiguration("http://localhost:10000")))
{
server.Configuration.Routes.MapHttpRoute("default", "{controller}");
server.OpenAsync();
Console.Read();
}

接下来我们将定义一个HttpSelfHostServer来实现SelfHost

API是不是相比SelfHost更方便?

using (var server = new MyHttpSelfHostServer("http://localhost:10000"))
{
server.Configuration.Routes.MapHttpRoute("default", "{controller}");
server.OpenAsync();
Console.Read();
}

再看看我们具体的MyHttpSelfHostServer如何实现

public class MyHttpSelfHostServer : HttpServer
{
private string _url;
public MyHttpSelfHostServer(string url)
{
_url = url;
} public async void OpenAsync()
{
var binding = new HttpBinding();
var listener = binding.BuildChannelListener<IReplyChannel>(new Uri(_url));
listener.Open();//开启监听
var reply = listener.AcceptChannel();
reply.Open();//开启通信通道
while (true)
{
var request = reply.ReceiveRequest();//接受到请求
//获取HttpRequestMessage
var method = request.RequestMessage.GetType().GetMethod("GetHttpRequestMessage");
var requestMessage = method.Invoke(request.RequestMessage, new object[] { true }) as HttpRequestMessage;
var response = await base.SendAsync(requestMessage, new CancellationTokenSource().Token);
request.Reply(CreateMessage(response));//回复消息
}
} Message CreateMessage(HttpResponseMessage response)
{
var type = Type.GetType("System.Web.Http.SelfHost.Channels.HttpMessage,System.Web.Http.SelfHost");
return (Message)Activator.CreateInstance(type, response);
}
}

最后我们来请求一下地址:http://localhost:10000/Demo

备注:

  • 文章中的代码并非完整,一般是经过自己精简后的.

  • 本篇内容使用MarkDown语法编辑

首发地址:http://neverc.cnblogs.com/p/5949974.html

[Web API] Web API 2 深入系列(2) 消息管道的更多相关文章

  1. ASP.NET Web API - ASP.NET MVC 4 系列

           Web API 项目是 Windows 通信接口(Windows Communication Foundation,WCF)团队及其用户激情下的产物,他们想与 HTTP 深度整合.WCF ...

  2. 如何用Baas快速在腾讯云上开发小程序-系列1:搭建API & WEB WebSocket 服务器

    版权声明:本文由贺嘉 原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/221059001487422606 来源:腾云阁 h ...

  3. Java web与web gis学习笔记(二)——百度地图API调用

    系列链接: Java web与web gis学习笔记(一)--Tomcat环境搭建 Java web与web gis学习笔记(二)--百度地图API调用 JavaWeb和WebGIS学习笔记(三)-- ...

  4. HTML5权威指南--Web Storage,本地数据库,本地缓存API,Web Sockets API,Geolocation API(简要学习笔记二)

    1.Web Storage HTML5除了Canvas元素之外,还有一个非常重要的功能那就是客户端本地保存数据的Web Storage功能. 以前都是用cookies保存用户名等简单信息.   但是c ...

  5. 我所理解的RESTful Web API [Web标准篇]

    REST不是一个标准,而是一种软件应用架构风格.基于SOAP的Web服务采用RPC架构,如果说RPC是一种面向操作的架构风格,而REST则是一种面向资源的架构风格.REST是目前业界更为推崇的构建新一 ...

  6. 重构Web Api程序(Api Controller和Entity)续篇

    昨天有写总结<重构Web Api程序(Api Controller和Entity)>http://www.cnblogs.com/insus/p/4350111.html,把一些数据交换的 ...

  7. web api写api接口时返回

    web api写api接口时默认返回的是把你的对象序列化后以XML形式返回,那么怎样才能让其返回为json呢,下面就介绍两种方法: 方法一:(改配置法) 找到Global.asax文件,在Applic ...

  8. Google Maps API Web Services

    原文:Google Maps API Web Services 摘自:https://developers.google.com/maps/documentation/webservices/ Goo ...

  9. asp.net web api 构建api帮助文档

    1 概要 创建ASP.NET Web Api 时模板自带Help Pages框架. 2 问题 1)使用VS创建Web Api项目时,模板将Help Pages框架自动集成到其中,使得Web Api项目 ...

随机推荐

  1. doduicms 手机和pc同步 链接处理

    sitem.aspx 加上 Session.Add("ismobile", "1"); string mobile = HttpContext.Current. ...

  2. Unity - Apk包的代码与资源提取

    最近在研究如何给Unity游戏进行加密,让别人不能轻易破解你的apk包,不过网上的加密方法都是有对应的破解方法~_~!!结果加密方法没找到好的,逆向工程倒会了不少.今天就来讲解如何提取一个没做任何保护 ...

  3. asp.net中的<%%> <%#%> <%=%>形式的详细用法 (转载)

    博客分类: ASP.NET   一. <%%>这种格式实际上就是和asp的用法一样的,只是asp中里面是vbscript或者javascript代码,而在asp.net中是.net平台下支 ...

  4. 修改sql数据库文件 物理文件名称

    -- 允许配置高级选项 EXEC sp_configure 'show advanced options', 1 GO -- 重新配置 RECONFIGURE GO -- 启用xp_cmdshell ...

  5. SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/D:/MyEclipseWorkSpace/Emps/WebRoot/WEB-INF/lib/slf4j-nop-1.5.6.

    错误的是HQL语句,注意写类名属性名无误,条件无误.

  6. python获取当前时间的用法

    1.先导入库:import datetime 2.获取当前日期和时间:now_time = datetime.datetime.now() 3.格式化成我们想要的日期:strftime() 比如:“2 ...

  7. 大家一起Aop

    一.前言 1.在项目中无处不充斥着记录日志的代码,各种try catch,实在是有点看着不爽.这不,果断要想法子偷个懒儿. 二.摘要 鄙人不才,先总结一下个人想到的可实现AOP的几种思路: 1.通过继 ...

  8. 新人入职100天,聊聊自己的经验&教训

    这篇文章讲了什么? 如题,本屌入职100天之后的经验和教训,具体包含: 对开发的一点感悟. 对如何提问的一点见解. 对Google开发流程的吐槽. 如果你 打算去国外工作. 对Google的开发流程感 ...

  9. CentOS On VirtualBox

    背景 后台开发需要随时与服务器交互,本人使用Mac开发.但是不愿意在Mac上直接安装redis以及mysql等等工具.所以选择在VirtualenvBox下安装一个服务器系统,并且使用ssh与其连接. ...

  10. [oracle]逗号(或分号等)间隔的列,按这一列劈分后转多行

    今天遇到个需求,要匹配两个表, 但是关联的字段,在另一个表中是放在一个字段中用分号分割的 怎么全部匹配呢? 后来在网上搜到了, 记录下 SELECT cp.ES_EXTNUMBER, cp.ES_AG ...