How to get the response body if the server responds 404? Below, the code to which the request is sent, when responding, throws a WebException in which there is no response body, although if you catch the request with Fiddler, there is a body.

public static string Send(string body, string QueryUri, string ReqMet) { var BodyByte = Encoding.UTF8.GetBytes(body); var Request = WebRequest.Create(QueryUri) as HttpWebRequest; Request.Method=ReqMet; Request.ContentType="application/json"; using (var requestStream = Request.GetRequestStream()) { requestStream.Write(BodyByte, 0, BodyByte.Length); } using(var response = (HttpWebResponse)Request.GetResponse()) { using(var reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } } 

1 answer 1

  public static string Send(string body, string QueryUri, string ReqMet) { var BodyByte = Encoding.UTF8.GetBytes(body); var Request = WebRequest.Create(QueryUri) as HttpWebRequest; Request.Method = ReqMet; Request.ContentType = "application/json"; using (var requestStream = Request.GetRequestStream()) { requestStream.Write(BodyByte, 0, BodyByte.Length); } try { using (var response = (HttpWebResponse) Request.GetResponse()) { using (var reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } } catch (WebException ex) { using (var reader = new StreamReader(ex.Response.GetResponseStream())) { return reader.ReadToEnd(); } } }