2

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?

2
  • 1
    You can use an HttpRequestMessage instead. And use it like this : _httpClient.Client.SendAsync(myRequest) Commented Sep 24, 2018 at 14:31
  • 2
    My answer here gives a code example of how to implement @Kalten's approach. Commented Sep 24, 2018 at 14:39

1 Answer 1

6

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>();
Sign up to request clarification or add additional context in comments.

2 Comments

How can we get configuration values from the DelegatingHandler?
@Jimenemex by DI

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.