skip to Main Content

Assume a HttpClient having been set up to look like the following (as per standard called with a factory):

builder.Services.AddControllersWithViews();
builder.Services.AddHttpClient("weather", weather =>
{
     weather.BaseAddress = new Uri("http://api.openweathermap.org/data/2.5");
     weather.Timeout = TimeSpan.FromSeconds(15);
}).SetHandlerLifetime(TimeSpan.FromSeconds(15));

Now when using the HttpClient to call an API I would like to reference the API key directly from the client rather than instantiating or defining it in the separate controller class. How would I go about doing this? Is it possible and if yes how would I reference it?

2

Answers


  1. Use IOptions pattern:

    public class HttpClientSettings
    {
        public string ApiKey{ get; set; }
    }
    

    In appsettings:

    {
      "HttpClientSettings": {
        "ApiKey": "Value1"
      }
    }
    

    In program.cs/startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<HttpClientSetting>(Configuration.GetSection(nameof(HttpClientSettings)));
    }
    

    In the client:

    public class TestService
    {
        private readonly HttpClient _httpClient;
        private readonly HttpClientSettings _httpClientSettings;
    
        public TestService(HttpClient httpClient, IOptions<MySettings> settings)
        {
            _httpClient = httpClient;
            _httpClientSettings= settings.Value;
        }
    
        public async Task<string> DoSomethingAsync()
        {
            httpClient.DefaultRequestHeaders.Add("Api-Key", _httpClientSettings.ApiKey);
    ...
        
        }
    
    }
    
    Login or Signup to reply.
  2. It’s possible to add APIKey when you’re adding HttpClient to DI, Actually it’s the best way:

    
    builder.Services.AddHttpClient("weather", weather =>
    {
        weather.BaseAddress = new Uri("http://api.openweathermap.org/data/2.5");
        weather.Timeout = TimeSpan.FromSeconds(15);
    
        weather.DefaultRequestHeaders.TryAddWithoutValidation("APIKEY", builder.Configuration["HttpClient:APIKey"]);
    
    }).SetHandlerLifetime(TimeSpan.FromSeconds(15));
    
    

    By so, all Apis that are calling by HttpClient (weather) will use the APIKey, and no need to worry about it anymore.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search