HttpWebRequest WebException ProtocolError

I am trying to understand something about exception handling using HttpWebRequest.

I have a client library and it makes a request to the WebAPI controller,

HttpWebRequest r = (HttpWebRequest)WebRequest.Create(url);

r.Method = "POST";
r.ContentType = "application/json";

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

I know that the request will throw an exception and contain the message "entity already exists - 1234".

When I get an answer,

using (HttpWebResponse response = (HttpWebResponse)r.GetResponse())
{
    if (response.StatusCode == HttpStatusCode.OK)
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            return reader.ReadToEnd();

     return "Invalid"; 
 }

I get a WebException throw. So the calling request has a try..catch in it. And I get a WebException. What I get is a protocol error, not an internal internal server 500 error (using the correct status codes to represent the message comes later). Now, if I read the WebException answer, it contains my message and stack.

Questions

  • Why don't I get a status code 500 in my answer, why does it throw a protocol error?
  • ?

, , .. , , , , .

+4
1

An 500 internal server error , API , , , " ".

API, . .

0

All Articles