Setting request headers per request with IHttpClientFactory

4.6k Views Asked by At

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?

1

There are 1 best solutions below

2
On

You can use an DelegatingHandler to add an header to each request the HttpClient will make.

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);
    }
}

}

You register the hanlder using :

service.AddTransient<HeaderHandler>()
    .AddHttpClient<MyHttpClient>()
    .AddHttpMessageHandler<HeaderHandler>();