3

I am trying to make a web API call by using HttpClient but getting Not authorized error. I am passing key in the header but still, it gives me this error. I can see my key in fiddler trace.

If I use WebClient then I am getting a successful response. request is same in both methods.

Using HttpClient:

#region HttpClient

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("apiKey", "MyKey");

    var content = JsonConvert.SerializeObject(request);
    var response = await client.PostAsJsonAsync("https://MyUrl", content);

    if (response.IsSuccessStatusCode)
    {
        deliveryManagerQuoteResponse = await response.Content.ReadAsAsync<DeliveryManagerQuoteResponse>();
    }
    else
    {
        var reasonPhrase = response.ReasonPhrase;
        if (reasonPhrase.ToUpper() == "NOT AUTHORIZED")
        {
            throw new KeyNotFoundException("Not authorized");
        }
    }
}

#endregion

Using WebClient:

#region WebClient

// Create string to hold JSON response
string jsonResponse = string.Empty;

using (var client = new WebClient())
{
    try
    {
        client.UseDefaultCredentials = true;
        client.Headers.Add("Content-Type:application/json");
        client.Headers.Add("Accept:application/json");
        client.Headers.Add("apiKey", "MyKey");

        var uri = new Uri("https://MyUrl");
        var content = JsonConvert.SerializeObject(request);

        var response = client.UploadString(uri, "POST", content);
        jsonResponse = response;
    }
    catch (WebException ex)
    {
        // Http Error
        if (ex.Status == WebExceptionStatus.ProtocolError)
        {
            var webResponse = (HttpWebResponse)ex.Response;
            var statusCode = (int)webResponse.StatusCode;
            var msg = webResponse.StatusDescription;
            throw new HttpException(statusCode, msg);
        }
        else
        {
            throw new HttpException(500, ex.Message);
        }
    }
}

#endregion
6
  • 4
    First things first, you are using HttpClient wrong. Secondly, are you using fiddler to see what both requests look like? You should be able to see that the headers will look different. Try just adding: client.DefaultRequestHeaders.Add("apiKey", "MyKey"); Commented Sep 27, 2017 at 17:45
  • 1
    That worked. Thank you. Commented Sep 27, 2017 at 17:50
  • Glad to hear it worked! Commented Sep 27, 2017 at 17:59
  • @maccettura, add the answer so he can mark it as accepted. ;) . Commented Sep 27, 2017 at 18:00
  • 1
    Thank you @maccettura for the link/reference to "You're using HttpClient wrong ...." valuable info that should not be lost/overlooked ! Commented Sep 28, 2017 at 19:18

1 Answer 1

5

First things first, you are using HttpClient wrong.

Secondly, are you using fiddler to see what both requests look like? You should be able to see that the headers will look different. Right now you are using the Authorization Headers which will actually do something different than you want. All you need to do is simply add a regular 'ol header:

client.DefaultRequestHeaders.Add("apiKey", "MyKey");
Sign up to request clarification or add additional context in comments.

1 Comment

Hope people take the time to read the link "You're using HttpClient wrong ...." . Valuable info that is not intuitive and does not directly address the problem the user was asking about.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.