[英]How to add a header in HTTP request c#?
I need to send a request and to authenticate i need to add a header. I'm new to all this and probably its a stupid question but please i really need this.我需要发送一个请求并进行身份验证,我需要添加一个 header。我是这一切的新手,可能这是一个愚蠢的问题,但我真的需要这个。 I tried to use HttpHeaders header = new HttpHeaders();
我尝试使用HttpHeaders header = new HttpHeaders();
but theres an error.但是有一个错误。
var httpClient = new HttpClient();
HttpHeaders headers = new HttpHeaders(); // <- error
var request = httpClient.GetAsync("link").Result;
Console.ReadKey();
The error is Cannot create an instance of the abstract class or interface
错误是Cannot create an instance of the abstract class or interface
I give you an example.我给你举个例子。 I make a request to get access token and then add Authorization
to the header.我请求获取访问令牌,然后将Authorization
添加到 header。
To request the access token:要请求访问令牌:
var tokenClient = new User()
{
username= "admin",
password= "@dmin",
};
HttpResponseMessage response = await client.PostAsJsonAsync<string>("https://api.example.com/api/v1/token", tokenClient);
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsStringAsync().Result;
}
Then to add Authorization
to the header, add the following code:然后给header添加Authorization
,添加如下代码:
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + access_token);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.