GThree
GThree

Reputation: 3502

Issue in calling web API by using HttpClient Vs. WebClient C#

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

Upvotes: 3

Views: 5915

Answers (1)

maccettura
maccettura

Reputation: 10818

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");

Upvotes: 5

Related Questions