WebApi2官网学习记录--HTTP Message Handlers
Message Handlers是一个接收HTTP Request返回HTTP Response的类,继承自HttpMessageHandler
通常,一些列的message handler被链接到一起。第一个handler收到http request做一些处理,然后将request传递到下一个handler。在某时刻,response被创并返回。这种模式被称为delegating hanlder

服务端消息处理
在服务端,WebAPI管道使用一些内建的message handlers
HttpServer从主机获取requestHttpRoutingDispacher基于路由分配requestHttpControllerDispacher发送request到WebAPI的controller
可以在pipline中自定义message handlers,如图,展示了两个自定义的handler

自定义 Message Handlers
自定义message handler需要实现System.Net.Http.DelegatingHandler接口,并重载SendAsync方法。
Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken);
典型的实现通过一些流程:
- 处理request message
- 调用
base.SendAsync将request传递到内部的handler(inner handler) - 内部的handler返回一个response message(这步是异步的)
- 处理response并返回给调用者
一个简单的例子:
public class MessageHandler1 : DelegatingHandler
{
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
Debug.WriteLine("Process request");
// Call the inner handler.
var response = await base.SendAsync(request, cancellationToken);
Debug.WriteLine("Process response");
return response;
}
}
当然,也可以跳过inner handler,直接创建一个response(这种方式对于验证request很有用)
public class MessageHandler2 : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
// Create the response.
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("Hello!")
};
// Note: TaskCompletionSource creates a task that does not contain a delegate.
var tsc = new TaskCompletionSource<HttpResponseMessage>();
tsc.SetResult(response); // Also sets the task state to "RanToCompletion"
return tsc.Task;
}
}

添加Handler到Pipeline
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MessageHandlers.Add(new MessageHandler1());
config.MessageHandlers.Add(new MessageHandler2());
// Other code not shown...
}
}
Message Handler被调用的顺序与添加到MessageHandlers集合的顺序相同,由于是嵌套的response message消息传播的方向正好与此相反。
对于inner handlers我们不需要设置,WebAPI框架会自动连接。
Per-Route Message Handlers
既可以在 HttpConfiguration.MessageHandlers集合中设置Handlers应用到globally范围,也可以在指定路由上添加一个message handler
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "Route1",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "Route2",
routeTemplate: "api2/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: null,
handler: new MessageHandler2()// per-route message handler
);
config.MessageHandlers.Add(new MessageHandler1()); // global message handler
}
}
通过以上配置,如果URI匹配"Route2",请求将被分配到MessageHandler2。如下图所示:

注意:MessageHandler2会替代默认的HttpControllerDispatcher,匹配"Route2"的request将不能找到对应的controller,可以通过手动建立HttpControllerDispatcher来解决。
// List of delegating handlers.
DelegatingHandler[] handlers = new DelegatingHandler[] {
new MessageHandler3()
};
// Create a message handler chain with an end-point.
var routeHandlers = HttpClientFactory.CreatePipeline(
new HttpControllerDispatcher(config), handlers);
config.Routes.MapHttpRoute(
name: "Route2",
routeTemplate: "api2/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: null,
handler: routeHandlers
);

使用Message Handler的例子
跳过inner handler 直接返回response
/// <summary>
/// 跳过inner handler 直接返回response
/// </summary>
public class MyMessageHandler2:DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// Create the response.
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("Hello!")
}; // Note: TaskCompletionSource creates a task that does not contain a delegate.
var tsc = new TaskCompletionSource<HttpResponseMessage>();
tsc.SetResult(response); // Also sets the task state to "RanToCompletion"
// return tsc.Task;
return base.SendAsync(request,cancellationToken);
}
}
重写Request method
/// <summary>
/// 重写Request method
/// </summary>
public class MethodOverrideHandler:DelegatingHandler
{
readonly string[] _methods = { "DELETE", "HEAD", "PUT" };
const string _header= "X-HTTP-Method-Override"; protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Method == HttpMethod.Post && request.Headers.Contains(_header))
{
var method = request.Headers.GetValues(_header).FirstOrDefault();
if (_methods.Contains(method, StringComparer.InvariantCulture))
{
request.Method = new HttpMethod(method);
}
}
return base.SendAsync(request, cancellationToken);
}
}
WebApi2官网学习记录--HTTP Message Handlers的更多相关文章
- WebApi2官网学习记录--HttpClient Message Handlers
在客户端,HttpClient使用message handle处理request.默认的handler是HttpClientHandler,用来发送请求和获取response从服务端.可以在clien ...
- WebApi2官网学习记录--- Authentication与Authorization
Authentication(认证) WebAPI中的认证既可以使用HttpModel也可以使用HTTP message handler,具体使用哪个可以参考一下依据: 一个HttpModel可以 ...
- WebApi2官网学习记录---批量处理HTTP Message
原文:Batching Handler for ASP.NET Web API 自定义实现HttpMessageHandler public class BatchHandler : HttpMess ...
- WebApi2官网学习记录---Cookie
Cookie的几个参数: Domain.Path.Expires.Max-Age 如果Expires与Max-Age都存在,Max-Age优先级高,如果都没有设置cookie会在会话结束后删除cook ...
- WebApi2官网学习记录---Tracing
安装追踪用的包 Install-Package Microsoft.AspNet.WebApi.Tracing Update-Package Microsoft.AspNet.WebApi.WebHo ...
- WebApi2官网学习记录---异常处理
HttpResponseException 当WebAPI的控制器抛出一个未捕获的异常时,默认情况下,大多数异常被转为status code为500的http response即服务端错误. Http ...
- WebApi2官网学习记录---Html Form Data
HTML Forms概述 <form action="api/values" method="post"> 默认的method是GET,如果使用GE ...
- WebApi2官网学习记录---Configuring
Configuration Settings WebAPI中的configuration settings定义在HttpConfiguration中.有一下成员: DependencyResolver ...
- WebApi2官网学习记录---单元测试
如果没有对应的web api模板,首先使用nuget进行安装 例子1: ProductController 是以硬编码的方式使用StoreAppContext类的实例,可以使用依赖注入模式,在外部指定 ...
随机推荐
- Web文件管理:elFinder.Net(支持FTP)
elFinder 是一个基于 Web 的文件管理器,灵感来自 Mac OS X 的 Finder 程序. elFinder.Net是.Net版本的一个Demo,使用ASP.NET MVC 4集成,可以 ...
- (转)SQL Server 2005附加2008的数据库
1. 生成for 2005版本的数据库脚本 2008 的manger studio -- 打开"对象资源管理器"(没有的话按F8), 连接到你的实例 -- 右键要转到2005 ...
- ArcGIS Server Manager登陆不了
我很是郁闷,安装都好了(post安装完成之后它要我将 相关的用户(我在这里安装的时候已指定) 添加到 agsadmin和agsusers两个用户组中.都做好了, 我甚至将刚刚的用户和用户组都删掉,重新 ...
- 1 Linux平台下快速搭建FTP服务器 win7下如何建立ftp服务器
百度经验连接(亲测可用) http://jingyan.baidu.com/article/380abd0a77ae041d90192cf4.html win7下如何建立ftp服务器 http://j ...
- JSTL核心标签库
1.set:给web域设置值的 <c:set var="lang" value="Java" scope="page">< ...
- NOIP201504推销员
#include<iostream> #include<cstring> #include<algorithm> #include<cmath> #in ...
- jquery1.9学习笔记 之层级选择器(三)
下一个相邻选择器(“prev + next”) 描述:选择所有给出祖先选择器的子孙选择器. 例子: <!doctype html> <html lang='zh'> <h ...
- quartz spring
简单例子可参考 http://yangpanwww.iteye.com/blog/797563 http://liuzidong.iteye.com/blog/1118992 关于时间配置可参考另一篇 ...
- Linux平台Makefile文件的编写基础篇(转)
目的: 基本掌握了 make 的用法,能在Linux系统上编程.环境: Linux系统,或者有一台Linux服务器,通过终端连接.一句话:有Linux编译环境.准备: ...
- Pick two points at random from the interior of a unit square, what is the expected distance between them?
My solution is as folllowing. This integration is hard to solve. I googled it, and found the result ...