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类的实例,可以使用依赖注入模式,在外部指定 ...
随机推荐
- Spring 学习笔记02
用spring实现一个论坛基本功能 1 运行环境 Linux:Ubun 14.04 64bit IDE:IntelliJ IDEA 14.03 JDK:1.7.40 MySQL:5.5.44 Tomc ...
- HDU 2063 裸奔的二分图最大匹配
#include <cstdio>#include <cmath>#include <algorithm>#include <iostream>#inc ...
- uva 759 - The Return of the Roman Empire
#include <cstdio> #include <string> #include <map> using namespace std; ; , , , , ...
- POJ1276:Cash Machine(多重背包)
Description A Bank plans to install a machine for cash withdrawal. The machine is able to deliver ap ...
- python中os.walk()遍历目录中所有文件
之前一直用判断目录和文件的递归方法来获取一个目录下的所有文件,后来发现python里面已经写好了这个函数,不需要自己递归获取了,记录下os.walk()函数的用法 目的:获取path下所有文件,返回由 ...
- set{变量 = value;}get{return 变量;}
形如: public string _customValue { set { _customValue = value; } get { re ...
- App 冷启动:给 Android 的 Activity 添加一个背景
2016/8/8 11:11:18 # 纠错 之前写的这篇内容的知识点有误,给大家造成了误导,深感抱歉. android 中给 Activity 设置背景的方法是在 style 文件中设置 windo ...
- EFI主板和GPT分区表安装系统以及转换GPT分区表的方法
现在硬盘越来越大,而原来的MBR分区方式,超过2T的硬盘就会识别不全,只有使用GPT的方式才可以,但是GPT如果用原来的BIOS是无法引导装系统了,不过如果你的主板支持EFI,那么可以用GPT+EFI ...
- Log4j MDC Tomcat下报异常org.apache.log4j.helpers.ThreadLocalMap
严重: The web application [/qdgswx] created a ThreadLocal with key of type [org.apache.log4j.helpers.T ...
- github恢复
一.查看修改日志信息 1)git log:显示最近到最远的提交日志 添加参数--pretty=oneline:查看简单的日志信息. 二.进行恢复到先前版本 1)在Git中,HEAD表示当前版本,上一个 ...