我正在使用带有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
实例进行的每个后续请求设置请求标头。如何在每个请求的基础上设置标题?
答案 0 :(得分:2)
您可以使用DelegatingHandler
向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>();