加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-core – .NET Core HttpClient是否具有拦截器的概念?

发布时间:2020-12-16 06:55:31 所属栏目:asp.Net 来源:网络整理
导读:我想围绕从我的ASP.NET核心应用程序通过HttpClient进行的所有调用包含一些时序逻辑,包括从第三方库调用. .NET Core中的HttpClient是否有我可以插入的东西来在每个请求上运行一些代码? 解决方法 是的,它确实. HttpClient通过DelegatingHandler链生成HTTP请求
我想围绕从我的ASP.NET核心应用程序通过HttpClient进行的所有调用包含一些时序逻辑,包括从第三方库调用.

.NET Core中的HttpClient是否有我可以插入的东西来在每个请求上运行一些代码?

解决方法

是的,它确实. HttpClient通过DelegatingHandler链生成HTTP请求.要拦截HttpClient请求,可以将带有覆盖的SendAsync方法的派生处理程序添加到该链.

用法:

var handler = new ExampleHttpHandler(fooService);

var client = new HttpClient(new ExampleHttpHandler(handler));

var response = await client.GetAsync("http://google.com");

执行:

public class ExampleHttpHandler : DelegatingHandler
{
    //register the handler itself in DI to inject dependencies
    public ExampleHttpHandler(FooService service) : this(service,null)
    {
    }

    public ExampleHttpHandler(FooService service,HttpMessageHandler innerHandler)
    {
        //default handler should be the last!
        InnerHandler = innerHandler ?? new HttpClientHandler();
    }

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,CancellationToken cancellationToken)
    {
        //add any logic here
        return await base.SendAsync(request,cancellationToken);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读