用于预先请求的Web Api处理程序(Web Api Handler for pre

编程入门 行业动态 更新时间:2024-10-27 00:30:17
用于预先请求的Web Api处理程序(Web Api Handler for pre-request)

我使用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.

更多推荐

本文发布于:2023-08-08 00:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466727.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:程序   Api   Web   Handler   pre

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!