title: HttpWebRequest WebException ProtocolError
body: <p>I'm trying to understand something about exception handling with a <code>HttpWebRequest</code>.</p>
  <p>I have a client library and it's making a request to a WebAPI controller;</p>
  <pre><code>HttpWebRequest r = (HttpWebRequest)WebRequest.Create(url);
  
  r.Method = &quot;POST&quot;;
  r.ContentType = &quot;application/json&quot;;
  
  foreach (var header in request.Headers)
  {
       r.Headers.Add(header.Key, header.Value.ToString());
  }
  
  r.ContentLength = request.RequestBody.Length;
  
  using (StreamWriter writer = new StreamWriter(r.GetRequestStream()))
      writer.Write(request.RequestBody);
  </code></pre>
  <p>I know the request will throw an exception, and contain the message <code>entity already exists - 1234</code>.</p>
  <p>When I get the response;</p>
  <pre><code>using (HttpWebResponse response = (HttpWebResponse)r.GetResponse())
  {
      if (response.StatusCode == HttpStatusCode.OK)
          using (StreamReader reader = new StreamReader(response.GetResponseStream()))
              return reader.ReadToEnd();
  
       return &quot;Invalid&quot;; 
   }
  </code></pre>
  <p>I get a <code>WebException</code> thrown. So, the caller of the request has a <code>try..catch</code> in it. And I get the <code>WebException</code>. What I get is a protocol error, not the <code>500 internal server error</code> that was thrown (using correct status codes to represent the message comes later). Now if I read the <code>Response</code> of the <code>WebException</code>, it does contain my message and the stacktrace.</p>
  <p><strong>Questions</strong></p>
  <ul>
  <li>Why do I not get a status code of <code>500</code> in my response, why does it throw a protocol error?</li>
  <li>Is there a more correct way of handling the request?</li>
  </ul>
  <p>I have searched around and found some people getting this issue when not using the correct headers etc. But as far as I can tell, I have added all the headers that I can and still get the same behavior.</p>