1

我正在使用带有IHttpClientFactory. 像这样:

// Startup.cs
services.AddHttpClient<MyHttpClient>()

// MyHttpClient.cs
public class MyHttpClient
{
    public MyHttpClient(HttpClient client)
    {
        Client = client;
    }

    public HttpClient Client { get; }
}

// MyService.cs
public class MyService {
    public MyService(MyHttpClient httpClient) {}

    public async Task SendRequestAsync(string uri, string accessToken) {
        _httpClient.Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
        await _httpClient.Client.GetAsync(uri);
    }
}

我不确定这是如何工作的。请求标头是仅为此请求设置,还是为使用此实例发出的每个后续请求设置httpClient。如何根据每个请求设置标头?

4

1 回答 1

5

您可以使用 anDelegatingHandler为将发出的每个请求添加标头HttpClient

public class HeaderHandler: DelegatingHandler
{
    public HeaderHandler()
    {
    }
    public HeaderHandler(DelegatingHandler innerHandler): base(innerHandler)
    {
    }

    protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        request.Headers.Add("CUSTOM-HEADER","CUSTOM HEADER VALUE");
        return await base.SendAsync(request, cancellationToken);
    }
}

}

您使用以下方式注册处理程序:

service.AddTransient<HeaderHandler>()
    .AddHttpClient<MyHttpClient>()
    .AddHttpMessageHandler<HeaderHandler>();
于 2018-09-24T14:44:35.237 回答