我有一个web服务,它返回一个http 500,在响应的正文中包含一些诊断信息。
我正在做类似这样的事情
Stream responseStream = null;
WebResponse _Response = null;
Stream responseStream = null;
HttpWebRequest _Request = null;
try
{
_Response = _Request.GetResponse();
responseStream = _Response.GetResponseStream();
}
catch {
//try to view the Request.GetResponse() body here.
}因为_Request.GetResponse()返回一个http 500,所以似乎没有一种方法可以查看响应体。根据HTTP 500 Response with Body?的说法,这是9年前Java语言中的一个已知问题。我想知道现在是否有办法在.NET中做到这一点。
发布于 2019-11-05 04:45:22
微软文档很好地描述了如果失败,HttpWebRequest.GetResponse会返回什么,你可以在这里查看https://docs.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest.getresponse?view=netframework-4.8
在您的示例中,我认为您需要检查并处理WebException。
Stream responseStream = null;
WebResponse _Response = null;
Stream responseStream = null;
HttpWebRequest _Request = null;
try
{
_Response = _Request.GetResponse();
responseStream = _Response.GetResponseStream();
}
catch (WebException w)
{
//here you can check the reason for the web exception
WebResponse res = w.Response;
using (Stream s = res.GetResponseStream())
{
StreamReader r= new StreamReader(s);
string exceptionMessage = r.ReadToEnd(); //here is your error info
}
}
catch {
//any other exception
}https://stackoverflow.com/questions/58700668
复制相似问题