WebAPI 消息处理器

由上图可以看出消息处理器的使用场合和使用方法。

使用场合:

  • HttpServer 得到请求时.
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MessageHandlers.Add(new MessageHandler1());
        config.MessageHandlers.Add(new MessageHandler2());

        // Other code not shown...
    }
}
  • HttpRoutingDispatcher 根据路由分发地址时.
  • HttpControllerDispatcher 向控制器发送请求时.
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
    }
}

 使用方法:委托的一种特例,可以像一环套一环

实现DelegatingHandler代码:

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;
    }
}

 

参考地址:http://www.asp.net/web-api/overview/advanced/http-message-handlers

posted @ 2016-02-18 17:01  haiziguo  阅读(699)  评论(0编辑  收藏  举报