如何使用 web api 在请求头中添加 api 密钥

Ste*_*ral 2 c# asp.net-web-api2

大家好,这是我第一次使用 web api,我希望你能指出我正确的方向。如何使用 web api 在请求头中添加 api 密钥?

我试图检查谷歌,但我不确定我是否在看正确的指南。这就是我发现的 >如何在 WebApi 中添加和获取 Header 值

我的目标是发出 GET 请求并在请求标头中添加 API 密钥。

Rag*_*ria 11

您始终在任何 API 请求的标头中都有键值对。例如,这里的标题为“api_key”,值为“1234”。您可以通过下面给出的方式将其添加到您的 Http 请求中。

    HttpClient httpClient = new HttpClient();
    HttpRequestMessage request = new HttpRequestMessage();
    request.RequestUri = "Your_get_URI";
    request.Method = HttpMethod.Get;
    request.Headers.Add("api_key", "1234");
    HttpResponseMessage response =  await httpClient.SendAsync(request);
    var responseString = await response.Content.ReadAsStringAsync();
    var statusCode = response.StatusCode;
Run Code Online (Sandbox Code Playgroud)


Ant*_* G. 6

如果您使用 DI,您可以通过在 Startup.cs 中进行一些设置来轻松注入已配置的 HttpClient

以下是配置 HttpClient 以与 Microsoft 的 App Insights api 结合使用的工作示例。当然,您必须根据需要更改标题。

public void ConfigureServices(IServiceCollection services)
{
    //Somewhere in the ConfigureSerices method.
    services.AddHttpClient("APPINSIGHTS_CLIENT", c => 
    {
        c.BaseAddress = "<API_URL_HERE>";
        c.DefaultRequestHeaders.Add("x-api-key", clientKey));
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,如果您注入 IHttpClientFactory 以供下游使用,并调用它,它将被配置并准备好使用,无需任何大惊小怪。

HttpClient client = factory.CreateClient("APPINSIGHTS_CLIENT"); 
Run Code Online (Sandbox Code Playgroud)