在ASP.NET 4.5 MVC 4 Web API项目中,我想添加一个自定义HttpMessageHandler
。我已经改变了WebApiConfig
类(在\ App_Satrt \ WebApiConfig.cs),具体如下:如何在Web API中实现HttpMessageHandler?
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: null,
handler: new MyCustomizedHttpMessageHandler()
);
}
}
然后我开发MyCustomizedHttpMessageHandler
:
public class MyCustomizedHttpMessageHandler : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
IPrincipal principal = new GenericPrincipal(
new GenericIdentity("myuser"), new string[] { "myrole" });
Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
return Task<HttpResponseMessage>.Factory.StartNew(() => request.CreateResponse());
}
}
然而,请求API(假设http://mylocalhost.com/api/values) ,总是返回状态码200,没有任何数据。我的意思是它永远不会去ValuesController.cs的'GET()'方法。
我错过了什么?我如何正确实施HttpMessageHandler
?
PS:已经看过这个:https://stackoverflow.com/a/12030785/538387,不帮我。
谢谢。解决方案(1)运行良好。但数字2,'新HttpControllerDispatcher()'说:** System.Web.Http.Dispatcher.HttpControllerDispatcher不包含一个构造函数,它需要0个参数** - 更新:我修复了您的代码。谢谢。 – Tohid 2013-03-04 17:43:28
我更新了我的上述帖子too.thanks。 – 2013-03-04 18:25:29
请将Cuong Le的回答添加到回答中:**要编写自定义消息处理程序,您应该从'System.Net.Http.DelegatingHandler'派生** – Tohid 2013-03-04 18:37:43