如何将 API 密钥添加到 ASP.NET MVC 应用程序中的 HttpClient?

问题描述 投票:0回答:2

假设

HttpClient
已设置为如下所示(根据工厂调用的标准):

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

现在,当使用

HttpClient
调用 API 时,我想直接从客户端引用 API 密钥,而不是在单独的控制器类中实例化或定义它。我该怎么做呢?是否可能,如果可以,我将如何引用它?

c# asp.net asp.net-mvc
2个回答
0
投票

使用 IOptions 模式:

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

在应用程序设置中:

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

在program.cs/startup.cs中

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

在客户端:

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

}

0
投票

在DI中添加HttpClient时可以添加APIKey,实际上这是最好的方法:


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

这样,所有通过HttpClient(天气)调用的Api都将使用APIKey,再也不用担心了。

© www.soinside.com 2019 - 2024. All rights reserved.