我使用Web Api 2.0的委托处理程序拦截所有Web Api调用,并且需要在执行操作之前采取行动。
我按照以下Microsoft Docs中的说明实施了代码:
public class MyHandler : DelegatingHandler { protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { // do something return base.SendAsync(request, cancellationToken); } }并注册处理程序:
config.MessageHandlers.Add(new MyHandler());但是这个代码是在控制器方法之后执行的,这不是我所需要的。 我想在之前执行处理程序,就像我正在执行 MVC旧操作过滤器的预执行方法一样。
注意我没有使用动作过滤器,因为在Microsfot Docs中他们说停止使用Web Api 2.0的动作过滤器,因为它们将被弃用。 那么,使用Web Api时有什么选择?
I am using the Delegating Handler of Web Api 2.0 to intercept all my Web Api calls and I need to act before the action is executed.
I implemented the code as explained on Microsoft Docs as following:
public class MyHandler : DelegatingHandler { protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { // do something return base.SendAsync(request, cancellationToken); } }And register the handler:
config.MessageHandlers.Add(new MyHandler());But this code is executed after the controller method, which is not what I need. I want to execute the handler before, like I was doing on the pre-execute method of the old Action Filters for MVC.
Note I am not using the Action Filters because on Microsfot Docs they said to stop using the Action Filters for Web Api 2.0 because they will be deprecated. So, what's the alternative when working with Web Api?
最满意答案
您的问题很可能是在不同任务中同时执行的。 那是因为你不await base.SendAsync()调用。
沿着这些线应该可能解决你的问题:
var response = await base.SendAsync(request, cancellationToken); return response;你已经实现的MessageHandler的执行是通过你通过config.MessageHandlers.Add(new MyHandler());注册的Web API管道来执行的config.MessageHandlers.Add(new MyHandler()); 并且应该独立于任何操作过滤器
如果您正在寻找附加信息,请看这里 。
Your Problem is most likely concurrent execution in different Tasks. That is because you do not await the base.SendAsync() Call.
Something along these lines should probably solve your problem:
var response = await base.SendAsync(request, cancellationToken); return response;The execution of the MessageHandler you've implemented is executed through the Web API pipeline to which you registered it through config.MessageHandlers.Add(new MyHandler()); and should be independent from any action filters
If you are looking for addtional information look here.
更多推荐
发布评论