Fork me on GitHub
AspNetWebApi管线中如果定义两种类型的消息处理程序(全局/路由)

AspNetWebApi管线中如果定义两种类型的消息处理程序(全局/路由)

在AspNetWebApi管线中存在两种类型的消息处理程序(Message Handler)

1.全局消息处理程序,所有的请求都将通过这些消息处理程序,全局的消息处理程序,通过HTTP配置的MessageHandlers.Add(消息处理程序),例如:

var config = New HttpConfiguration /HttpSelfHostHttpSelfHostConfiguration()
config.MessageHandlers.Add( new CustomMessageHandler());

2.路由消息处理程序,只有特定的请求才被定制的消息处理程序处理。,可以通过配置添加新路由实现

  这里以博文【WebApi应用】通过定制MessageHandler来添加对调用程序的授权验证 的demo为例

_config = new HttpSelfHostConfiguration("http://localhost:5555");
复制代码
_config.Routes.MapHttpRoute(
        name:"CustomeRouteName",
        routeTemplate: "api2/{controller}/{username}", //新路由
        defaults:  new { username = RouteParameter.Optional },
        constraints: null,
        handler: new CustomeMessageHandler  //定制的消息处理程序
);       
复制代码

 

"api2/{controller}/{username}" 为新的路由URL模板,定制的消息处理程序(handler)只处理通过该UrlTemplate进行请求的消息

虽然定义了新的路由,然后运行程序:提示异常The inner handler has not been assigned

 

之所以执行新路由时候出现该异常是因为我们没有为定制的消息处理程序指定内部Http响应消息的处理程序,所以修改ValiteKeyMessageHandler类,在构造函数指定响应消息的处理程序.

复制代码
 public class ValiteKeyMessageHandler: DelegatingHandler {
        public string AppKey { get; set; }
        public ValiteKeyMessageHandler(string key, System.Web.Http.SelfHost.HttpSelfHostConfiguration configuration) {
            this.AppKey = key;
            //{ 此处为我们修改的 } 
            //为定制的消息处理程序指定响应消息的内部处理程序
            InnerHandler = new System.Web.Http.Dispatcher.HttpControllerDispatcher(configuration);
        }

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) {
            if (!ValidateKey(request)) {
                var response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
                var task = new TaskCompletionSource<HttpResponseMessage>();
                task.SetResult(response);
                return task.Task;
            }
            return base.SendAsync(request, cancellationToken);
        }

        private bool ValidateKey(HttpRequestMessage message) {
            var query = message.RequestUri.ParseQueryString();
            string key = query["AppKey"];
            return (AppKey == key);
        }
}
复制代码

 

然后重新编程程序正常执行

 
 
分类: WebApi
posted on 2013-09-09 11:27  HackerVirus  阅读(570)  评论(0编辑  收藏  举报