如何实现在网页API HttpMessageHandler? [英] How to implement HttpMessageHandler in Web API?
问题描述
在一个ASP.NET MVC 4.5 4个Web API项目,我想添加自定义的 HttpMessageHandler
。我已经改变了 WebApiConfig
类(在\\ App_Satrt \\ WebApiConfig.cs),如下:
In an ASP.NET 4.5 MVC 4 Web API project, I want to add a custom HttpMessageHandler
. I've changed WebApiConfig
class (in \App_Satrt\WebApiConfig.cs), as follows:
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 ),总回报状态code 200,没有任何数据。我的意思是永远不会获取ValuesController.cs的GET()方法。
However, the request to the API (let's say http://mylocalhost.com/api/values), always returns status code 200, without any data. I mean it never gets to ValuesController.cs's 'GET()' method.
什么我错过了?我如何能实现 HttpMessageHandler
是否正确?
What have I missed? How can I implement HttpMessageHandler
properly?
PS:已经阅读这一个: http://stackoverflow.com/a/12030785/538387 ,没有按'T帮我。
PS: Have already read this one: http://stackoverflow.com/a/12030785/538387 , doesn't help me.
推荐答案
在这里,您正在创建一个 HttpMessageHandler
这短路请求,并没有让请求通过流水线的其余部分。相反,你应该创建一个 DelegatingHandler
。
Here you are creating a HttpMessageHandler
which short circuits the request and doesn't let the request pass through the rest of the pipeline. Instead, you should create a DelegatingHandler
.
还有一些在网页API2种消息处理管道。一个是普通的管道中,为所有路由所有请求通过等,其中一个可能有特定于某些航线的消息处理程序只。
Also there are 2 kinds of message handler pipelines in Web API. One is a regular pipeline in which all requests for all routes pass through and other where one could have message handlers specific to certain routes only.
-
尝试创建一个
DelegatingHandler
并将其添加到消息处理你的HttpConfiguration
列表:
Try to create a
DelegatingHandler
and add it to yourHttpConfiguration
's list of message handlers:
config.MessageHandlers.Add(new HandlerA())
如果您要添加的路由特定的消息处理程序,那么你可以做到以下几点:
If you want to add a route specific message handler, then you could do the following:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: null,
handler:
HttpClientFactory.CreatePipeline(
new HttpControllerDispatcher(config),
new DelegatingHandler[]{new HandlerA()})
);
此网页API海报显示管道流
这篇关于如何实现在网页API HttpMessageHandler?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!