Search code examples
c#windows-phone-8async-awaitdotnet-httpclient

Adding authorization to the headers


I have the following code:

...
AuthenticationHeaderValue authHeaders = new AuthenticationHeaderValue("OAuth2", Contract.AccessToken);
string result = await PostRequest.AuthenticatedGetData(fullUrl, null, authHeaders);
return result; 
...

public static async Task<string> AuthenticatedGetData(string url, FormUrlEncodedContent data, AuthenticationHeaderValue authValue)
{

    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authValue.Parameter);

    HttpResponseMessage response = await client.PostAsync(new Uri(url), data);

    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    response.EnsureSuccessStatusCode();
    string responseBody = await response.Content.ReadAsStringAsync();
    return responseBody;
}

The response = await part just continues an ongoing loop and nothing happens. Any ideas what I am doing wrong?

The question really is, how do I send the following header:

Authorization: OAuth2 ACCESS_TOKEN

to an external web api


Solution

  • This line

    client.DefaultRequestHeaders.Authorization = 
               new AuthenticationHeaderValue(authValue.Parameter);
    

    Will produce this header value

    Authorization: ACCESS_TOKEN
    

    Where ACCESS_TOKEN is the value of authValue.Parameter. You want to assign the value you passed instead to get the required header

    client.DefaultRequestHeaders.Authorization = authValue;
    

    Will produce

    Authorization: OAuth2 ACCESS_TOKEN