简体   繁体   English

如何使用HttpClient在Web API中传递标头值

[英]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.

相关问题 接收Web api方法使用HttpClient接受强类型参数时,如何传递JSON字符串? - How to pass JSON string when receiving Web api method is accepting strongly typed parameter using HttpClient? 如何在Web Api中使用带有响应的Httpclient获取对象 - How to get object using Httpclient with response Ok in Web Api 如何使用HttpClient在C#中调用Web API? - How can I call a web api in c# using HttpClient? 如何使用HttpClient将JSON数据发布到Web API - How to Post JSON data to a Web API using HttpClient 如何在 .net 核心中使用 HttpClient 读取标头值 - How to read header values with HttpClient in .net core 如何在 asp.net 核心中使用 web api 响应传递 HttpClient 响应 - How pass HttpClient response with web api response in asp.net core 使用消息处理程序和HttpClient的Web API身份验证 - Web API Authentication using Message Handler and HttpClient HttpClient将多个对象/变量传递到[HttpPost] Web API m - HttpClient Pass Multiple objects/variables to[HttpPost] Web API m 如何使用新的WCF REST HttpClient API设置GoogleLogin请求的Authorization标头 - How do I do set the Authorization header of a GoogleLogin request using the new WCF REST HttpClient API 使用Web API将导航属性值传递给URI的方式是什么? - What is the way to pass in navigation property values to URI using Web API?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM