[英]How to add api key in request header using web api
大家好,這是我第一次使用 web api,我希望你能指出我正確的方向。 如何使用 web api 在請求頭中添加 api 密鑰?
我試圖檢查谷歌,但我不確定我是否在看正確的指南。 這就是我發現的 > 如何在 WebApi 中添加和獲取 Header 值
我的目標是發出 GET 請求並在請求標頭中添加 API 密鑰。
您始終在任何 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;
如果您使用的是 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));
}
}
現在,如果您注入 IHttpClientFactory 以供下游使用,並調用它將被配置並准備好使用,而無需大驚小怪。
HttpClient client = factory.CreateClient("APPINSIGHTS_CLIENT");
試試這個,我希望這對你有用。
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());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.