【问题标题】:Does .NET Core HttpClient have the concept of interceptors?.NET Core HttpClient 有拦截器的概念吗?
【发布时间】:2017-02-09 07:12:33
【问题描述】:

我想围绕我的 ASP.NET Core 应用通过 HttpClient 进行的所有调用封装一些计时逻辑,包括从 3rd 方库进行的调用。

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

【问题讨论】:

  • 没有。如果我有一个 ASP.NET Core 应用程序,其中包含一个通过 HTTP 调用另一个服务器的库,我怎么知道该库调用另一个服务器需要多长时间。其他技术(Angular)具有拦截器的概念,只要发出传出 HTTP 请求,您就可以在其中接收回调。 .NET Core 有这个吗?谢谢

标签: asp.net-core .net-core


【解决方案1】:

是的,确实如此。 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
{
    //use this constructor if a handler is registered in DI to inject dependencies
    public ExampleHttpHandler(FooService service) : this(service, null)
    {
    }

    //Use this constructor if a handler is created manually.
    //Otherwise, use DelegatingHandler.InnerHandler public property to set the next handler.
    public ExampleHttpHandler(FooService service, HttpMessageHandler innerHandler)
    {
        //the last (inner) handler in the pipeline should be a "real" handler.
        //To make a HTTP request, create a HttpClientHandler instance.
        InnerHandler = innerHandler ?? new HttpClientHandler();
    }

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

顺便说一句,我建议将尽可能多的业务逻辑从自定义处理程序中移出,以简化对其进行单元测试。

【讨论】:

  • 我不确定这如何适用于整个问题。它看起来像是一种在您自己的代码中为每个请求进行回调的方法,该方法将使用 ExampleHttpHandler。但我看不出它会如何影响您使用的第三方库的内部行为。
  • @Zastai 这取决于图书馆。一个好的应该接受外部HttpClient 实例或处理程序作为可选参数。例如,Flurl 提供了这种可能性。
猜你喜欢
  • 2018-07-25
  • 1970-01-01
  • 1970-01-01
  • 2021-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
相关资源
最近更新 更多