D
D
demiash2020-08-26 17:41:14
C++ / C#
demiash, 2020-08-26 17:41:14

C# HttpWebRequest get server error description on StatusCode 500?

I send a request to the server, where the error is 500 and the description of the internal server error is returned in the browser In the WebException, I get
Status = ConnectionClosed (The request was aborted: The connection was closed unexpectedly.)
Accordingly, in WebException.Response = null

if there is an internal error?

the code:

HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost/test/request");
            webRequest.Credentials = CredentialCache.DefaultCredentials;
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] byte1 = encoding.GetBytes("SourceId=15");
            webRequest.ContentLength = byte1.Length;
            using (Stream newStream = webRequest.GetRequestStream()) {
                newStream.Write(byte1, 0, byte1.Length);
            }
            try {
                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                using (Stream receiveStream = webResponse.GetResponseStream()) {
                    Encoding encode = System.Text.Encoding.GetEncoding("windows-1251");
                    using (StreamReader readStream = new StreamReader(receiveStream, encode)) {
                        return readStream.ReadToEnd();
                    }
                }
            } catch (WebException ex) {
                HttpWebResponse httpResponse = (HttpWebResponse)ex.Response;
                if (ex.Response != null) {
                    using (Stream stream = ex.Response.GetResponseStream()) {
                        StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                        return reader.ReadToEnd();
                    }
                }

            }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
demiash, 2020-08-26
@demish

setting the request parameter helped: webRequest.ProtocolVersion = HttpVersion.Version10;
in this case, WebException.Response shows the content of the response
and WebException.Status is not ConnectionClosed (The request was aborted: The connection was closed unexpectedly.)
but ProtocolError (The remote server returned an error: (500) Internal server error.)

A
ayazer, 2020-08-26
@ayazer

No way. That is why this is an internal error, that the client does not need to know anything about it. In the browser, you can only see something if the server is running with a test configuration (when it displays a page with a stack trace in case of an error).
UPD
you can get the behavior you need something like this:

[ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet]
        public Task ChangeStatus()
        {
            throw new Exception("My test exception");
        }
    }

public class HttpResponseExceptionFilter : IActionFilter, IOrderedFilter
{
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Exception != null)
            {
                context.Result = new ObjectResult(new
                {
                    ErrorText = context.Exception.Message,
                    Stacktrace = context.Exception.StackTrace
                })
                { StatusCode = (int)HttpStatusCode.BadRequest };

                context.Exception = null;

                return;
         }
}

then by jerking the controller you will get back a 400 error with the content
{
"errorText": "My test exception",
"stacktrace": "stacktrace was here"
}
UPD2:
well, as far as I remember (and I may be wrong, but I can not double-check now) - HttpWebRequest will throw an exception for all non-200 http statuses. Because perhaps the stack trace will have to get not very beautiful
WebRequest request = ...;
try
{
  using var response = request.GetResponse();
  ...
}
catch (WebException e)
{
  using var webResponse = (HttpWebResponse)e.Response;
  var code = webResponse.StatusCode;
  var body = ...;

  //...

}

or use HttpClient, which throws an exception only if you ask

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question