用于 WebApi 中响应的 DelegatingHandler [英] DelegatingHandler for response in WebApi

查看:37
本文介绍了用于 WebApi 中响应的 DelegatingHandler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用几个委托处理程序(派生自 DelegatingHandler 的类)在请求被发送之前处理请求,例如验证签名等.这一切都非常好,因为我不'不必在所有调用上重复签名验证(例如).

I am currently using several delegation handlers (classes derived from DelegatingHandler) to work on the request before it is sent, for things like validating a signature etc. This is all very nice, because I don't have to duplicate signature validation on all calls (for example).

我想对来自同一网络请求的响应使用相同的原则.响应中是否有类似于 DelegatingHandler 的东西?一种在响应返回到方法之前捕获响应的方法,以某种方式?

I would like to use the same principle on the response from the same web request. Is there something similar to the DelegatingHandler for the response? A way to catch the response before it has returned to the method, in a way?

附加信息:我正在使用 HttpClient.PutAsync(...)

Additional information: I am calling a web api using HttpClient.PutAsync(...)

推荐答案

是的.您可以在延续任务中执行此操作.

Yes. You can do that in the continuation task.

我在这里进行解释.

例如,此代码(来自上面的博客)跟踪请求 URI 并向响应添加一个虚拟标头.

For example, this code (from the blog above) traces request URI and adds a dummy header to response.

public class DummyHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // work on the request 
       Trace.WriteLine(request.RequestUri.ToString());

       var response = await base.SendAsync(request, cancellationToken);
       response.Headers.Add("X-Dummy-Header", Guid.NewGuid().ToString());
       return response;
    }
}

这篇关于用于 WebApi 中响应的 DelegatingHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆