Sithis562
Sithis562

Reputation: 1

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. I tried to use 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

Upvotes: -1

Views: 880

Answers (1)

user18472331
user18472331

Reputation:

I give you an example. I make a request to get access token and then add Authorization to the 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:

var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + access_token);

Upvotes: 1

Related Questions