title: Issue in calling web API by using HttpClient Vs. WebClient C#
body: <p>I am trying to make a web API call by using <code>HttpClient</code> but getting <code>Not authorized</code> error. I am passing key in the header but still, it gives me this error. I can see my key in <code>fiddler trace</code>.</p>
  
  <p>If I use <code>WebClient</code> then I am getting a successful response. <code>request</code> is same in both methods.</p>
  
  <p><strong>Using HttpClient:</strong></p>
  
  <pre><code>#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&lt;DeliveryManagerQuoteResponse&gt;();
      }
      else
      {
          var reasonPhrase = response.ReasonPhrase;
          if (reasonPhrase.ToUpper() == "NOT AUTHORIZED")
          {
              throw new KeyNotFoundException("Not authorized");
          }
      }
  }
  
  #endregion
  </code></pre>
  
  <p><strong>Using WebClient:</strong></p>
  
  <pre><code>#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
  </code></pre>