微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我想围绕从我的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);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐