【问题标题】:How to correctly DI HttpClient into FlurlClient?如何正确地将 DI HttpClient 转换为 FlurlClient?
【发布时间】:2020-06-30 10:50:45
【问题描述】:

注册自定义消息处理程序似乎不适用于 FlurlClient。

    .. other setup logic
    /// <summary>
    /// Configures the application services.
    /// </summary>
    /// <param name="services">The service collection.</param>
    public override void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<ConsoleCorrelationIdHandler>();
        this.AddHttpClient<ICatalogService, CatalogService>(services, "http://httpbin.org");

    }

    private void AddHttpClient<TClient, TImplementation>(IServiceCollection services, string url = null)
        where TClient : class
        where TImplementation : class, TClient
        => services.AddHttpClient<TClient, TImplementation>(client =>
        {
            if (!string.IsNullOrWhiteSpace(url))
                client.BaseAddress = new Uri(url);
        })
            .AddHttpMessageHandler<ConsoleCorrelationIdHandler>(); // Appends CorrelationId to all outgoing HTTP requests.

在这里,我使用 ConsoleCorrelationIdHandler 注册了一个新的 HttpClient,它为所有传出请求添加了一个关联 id 标头。

public class CatalogService : ICatalogService
{
    private readonly IFlurlClient _httpClient;

    public CatalogService(HttpClient httpClient)
    {
        _httpClient = new FlurlClient(httpClient);
    }

    public async Task GetSomething()
    {
        var x = await this._httpClient.BaseUrl
            .AppendPathSegment("get")
            .GetJsonAsync();
        Console.WriteLine(JsonConvert.SerializeObject(x)); // Doesnt have CorrelationId header, which should have been added by handler.
    }
}

现在,当调用 GetSomething 时,IFlurlClient 确实具有已注册 httpclient 的基本 url,但不会调用消息处理程序。

【问题讨论】:

    标签: c# asp.net-core flurl


    【解决方案1】:

    让我们分解你的流利呼叫,看看发生了什么:

    _httpClient.BaseUrl
    

    你现在有一个字符串的引用。您在这里丢失了对客户的引用。

    .AppendPathSegment("get")
    

    在这里,您调用了一个字符串扩展方法,该方法创建一个Flurl.Url 对象并将get 附加到路径中。

    .GetJsonAsync();
    

    在这里,您正在调用Url 上的扩展方法,该方法创建FlurlRequest 并调用其GetJsonAsync 方法。在没有返回您要使用的客户端的引用的情况下,它将使用已注册的FlurlClientFactory 查找一个。在那里找不到,它会创建一个新的。

    简而言之,您在通话开始时丢失了对 FlurlClient 的引用。

    解决方法如下:

    var x = await this._httpClient
        .Request("get")
        .GetJsonAsync();
    

    【讨论】:

      猜你喜欢
      • 2018-07-19
      • 2021-11-21
      • 2018-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-19
      • 2015-03-18
      • 1970-01-01
      相关资源
      最近更新 更多