在 ASP.NET 4.5 MVC 4 Web API 项目中,我想添加一个自定义的HttpMessageHandler
. 我更改了WebApiConfig
类(在 \App_Satrt\WebApiConfig.cs 中),如下所示:
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 ,对我没有帮助。