'Add new option in runtime to already registered HttpClient service

In the startup of application I regiseter a new HttpClient named AmadeusSearchClient.

services.AddHttpClient<AmadeusSearchClient>(options =>
    {
        options.BaseAddress = new Uri(configuration.GetSection("AmadeusApi:BaseAddress").Value);
        options.Timeout = new TimeSpan(0, 0, int.Parse(configuration["AmadeusAccessToken:Timeout"]));
    });
    return services;

I'm receiving Amadeus access token using my other HttpClient called AmadeusAccessTokenClient, also registered in DI.

services.AddHttpClient<AmadeusAccessTokenClient>(options =>
    {
        options.BaseAddress = new Uri(configuration.GetSection("AmadeusApi:BaseAddress").Value);
        options.Timeout = new TimeSpan(0, 0, int.Parse(configuration["AmadeusAccessToken:Timeout"]));
    });
    return services;

To properly use AmadeusSearchClient, I need to add access token in the header of my request.

cancellationToken.ThrowIfCancellationRequested();

        var message = new HttpRequestMessage(
            HttpMethod.Get,
            "v1/travel/analytics/air-traffic/busiest-period?cityCode=BOS&period=2017");

        _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_token.Get()}");

        var response = await _httpClient.SendAsync(message, cancellationToken);

        var res = await response.Content.ReadAsStringAsync();

As you can see, in every request I have to add _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_token.Get()}"); DefaultRequestHeader manually. Is there any way to update the options of already registered AmadeusSearchClient when my application receives access token using AmadeusAccessTokenClient service?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source