2

I am trying to use an Api Rest (IGDB) making an Http Post Request with HttpClient; this request needs to have a key and a body. I am providing the key in HttpClient.DefaultRequestHeaders.Authorization, but I am getting a 401 status code, I know that the key works because I have used it in Postman and It worked fine, so I must be implementing it wrong.

My code:

private async Task<string> ConsumeApi()
        {
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Key Name", "Key Value");

            //Makes the client request only Json data
            //client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("aplication/json"));

            string theUri = "https://api-v3.igdb.com/games";


            var stringcontent = new StringContent("fields name", UnicodeEncoding.UTF8,"application/json");

            var response = await client.PostAsync("https://api-v3.igdb.com/games", stringcontent);
            return response.ToString();
        }

And these are Postman pictures of what I am trying to implement (works fine): Picture3

Jaime Santos
  • 437
  • 2
  • 10
  • 21

1 Answers1

1

AuthenticationHeaderValue

is not setting a header but is an authorization header. Set a normal header value, not one prefixed with Authentication.

Holden
  • 55
  • 6
TomTom
  • 61,059
  • 10
  • 88
  • 148
  • 1
    I don't see any system.net.http.header.[headervalue] without a prefix, which one should I use?. Also, why is AuthenticationHeaderValue incorrect, does it not represent authentication information in an authorization? – Jaime Santos May 24 '20 at 14:26
  • 1
    Ok, I found a way to do what you said, instead of: ```client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Key Name", "Key Value");``` I added it like this: ```client.DefaultRequestHeaders.Add("Key Name", "Key Value");```. Could you add it to your answer to make it more clear for those who see it? Thank you so much for the answer. – Jaime Santos May 25 '20 at 13:11