Set Authorization Header of HttpClient

42,027

Solution 1

I solved this by the following line of code.

client.DefaultRequestHeaders.Authorization =
       new AuthenticationHeaderValue("key", "=" + apiKey);

Solution 2

Not sure if this is still running, but basic auth key and something like a 64 hash authed key would be added to something like a REST call like:

var httpClient2 = new HttpClient();
var uri = new Uri("<someuri>");
var tokenKey = "<sometokenkey>");
var httpContent = new StringContent("<some body or serialized thing>", System.Text.Encoding.UTF8, "application/json");

httpClient2.BaseAddress = new Uri(uri);
httpClient2.DefaultRequestHeaders.Accept.Clear();
httpClient2.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", tokenKey);

response = await httpClient2.PostAsync(uri, httpContent);
Share:
42,027
Hakan Fıstık
Author by

Hakan Fıstık

Software Developer. Interested mainly in C#, .NET, Visual Studio, DDD, Design Patterns, and Agile.

Updated on May 20, 2021

Comments

  • Hakan Fıstık
    Hakan Fıstık almost 3 years

    I have the following code, and I want to set the Authorization of the post request to be like this:

    Authorization:key=somevalue

    using (HttpClient client = new HttpClient())
    {
         using (StringContent jsonContent = new StringContent(json))
         {
             jsonContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    
             using (HttpResponseMessage response = await client.PostAsync("https://android.googleapis.com/gcm/send", jsonContent))
             {
                var reponseString = await response.Content.ReadAsStringAsync();
             }
         }
    }
    

    how to do this? I am really struggling and the following statement

    client.DefaultRequestHeaders.Add("Authorization", "key=" + apiKey);
    

    thrown the following exception

    An exception of type 'System.FormatException' occurred in System.Net.Http.dll but was not handled in user code

  • P. Roe
    P. Roe over 5 years
    Depending on how the HTTP Client is stored this may not be thread safe. The error that will occur is "An item with the same key has already been added."
  • Hakan Fıstık
    Hakan Fıstık over 3 years
    I do not think this is the same problem, because you are using HttpWebRequest and I am using HttpClient
  • Cees
    Cees almost 3 years
    This solution worked great. i could even say new AuthenticationHeaderValue("Bearer", tokenKey); thanks alot!
  • TimTIM Wong
    TimTIM Wong over 2 years
    doesn't it add a space between key and =?
  • Hakan Fıstık
    Hakan Fıstık over 2 years
    @TimTimWong I do not know, It just worked for me :)