【发布时间】: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