[英]How to pass header values in web api using HttpClient
I'm new to ASP.NET Web API 2. I'm trying to access a third party API, so to access it first I need to pass a authorization Token in the header with the API URL. 我是ASP.NET Web API 2的新手。我试图访问第三方API,因此要首先访问它,我需要在标头中使用API URL传递授权令牌。 I'm able to access the data with Postman but I'm unable to do it with Code.
我可以使用Postman访问数据,但是无法使用Code进行访问。
Following is my code, I'm not sure if I'm going in the right direction. 以下是我的代码,我不确定我的方向是否正确。 Any help would be appreciated.
任何帮助,将不胜感激。
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("Url");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new HttpContext.Current.Request.Headers.Add("Authorization", "Token "+ "MyToken");
var re = Request;
var headers = re.Headers;
if (headers.Contains("Token"))
{
string token = headers.GetValues("Token").First();
}
return null;
}
If setting the default authorization header of the HttpClient
for all its requests use a AuthenticationHeaderValue
set on the client.DefaultRequestHeaders.Authorization
如果为所有请求设置
HttpClient
的默认授权标头,请在客户端上使用AuthenticationHeaderValue
设置client.DefaultRequestHeaders.Authorization
like in the following example... 就像下面的例子一样
//...other code removed for brevity
var tokenType = "Token"; //Other APIs use Bearer or other auth types.
var token = "MyToken";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenType, token);
//...other code removed for brevity.
Any requests made using the client will have an authorization header 使用客户端发出的任何请求都将具有授权标头
Authorization Token MyToken
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.