I'm using typed clients with IHttpClientFactory
. Like this:
// 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);
}
}
I'm unsure how this works. Will the request headers be set only for this request, or for every subsequent request that is made using this instance of httpClient
. How can I set header on a per request basis?
You can use an
DelegatingHandler
to add an header to each request theHttpClient
will make.}
You register the hanlder using :