HttpClient Authorization Header start with 'key='

57.8k Views Asked by At

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

3

There are 3 best solutions below

3
On BEST ANSWER

I solved this by the following line of code.

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

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:

HttpClient httpClient = new();
string tokenKey = "<some token key>";
httpClient.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Basic", tokenKey);
1
On

I had the same problem, I solved using :

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endPoint);

request.Headers["Authorization"] = "Basic jMxMTgwMWUzYWFkYTk4NjM2MjcyOTk3MDowYTU0N2I2NzliNWRkMjliN2I4NTFlMDBkY2Y2NjQzNzQ5OTIxYzZl";

where the string after Basic is an encoded string from Postman, the option is 'code'.

I hope this helps!