如何在Web API中的请求头中添加API密钥

6

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

我尝试查找谷歌,但不确定是否找到了正确的指南。我找到了以下内容 > 如何在WebApi中添加和获取标题值

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


在使用Get API时,您是否需要在标头中传递授权令牌? - Akhatarali Ansari
是的,您可以使用链接问题的方法...这样做没有任何问题! - Prashant Pimpale
3个回答

24

在任何API请求的标头中,您始终具有键值对。例如,在此处,您具有以“api_key”为键和以“1234”为值的标头。您可以按照以下方法将其添加到Http请求中。

HttpClient httpClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage();
request.RequestUri = new Uri("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;

1
如何在头部中使用“Key:Value”的编码字符串?我尝试将其添加到授权中,但无法正常工作。 - dellos
似乎值没有传递,但是键传递了? - Jarne

6
如果您正在使用 DI,您可以通过在 Startup.cs 中进行一些设置轻松地注入已配置的 HttpClient。
以下是一个可用的示例,用于配置与 Microsoft 的 App Insights api 一起使用的 HttpClient。当然,您需要根据需要更改标题。
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));
    }
}

现在,如果您注入IHttpClientFactory以供下游使用,并调用它,它将被配置并准备好使用,无需任何麻烦。
HttpClient client = factory.CreateClient("APPINSIGHTS_CLIENT"); 

-1

试一下这个,希望这对你有用。

            using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri("API URL");
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Authorization = new
                    System.Net.Http.Headers.AuthenticationHeaderValue("Pass your token value or API key");
                HttpResponseMessage response = await httpClient.GetAsync(endpoint);
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    string result = await response.Content.ReadAsStringAsync();
                    if (string.IsNullOrEmpty(result))
                        return "Success";
                    else
                        return result;
                }
                else if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    throw new UnauthorizedAccessException();
                }
                else
                {
                    throw new Exception(await response.Content.ReadAsStringAsync());
                }
            }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接