首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何查看Http500从System.Net.HttpWebRequest返回的正文

如何查看Http500从System.Net.HttpWebRequest返回的正文
EN

Stack Overflow用户
提问于 2019-11-05 04:34:26
回答 1查看 50关注 0票数 0

我有一个web服务,它返回一个http 500,在响应的正文中包含一些诊断信息。

我正在做类似这样的事情

代码语言:javascript
复制
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中做到这一点。

EN

回答 1

Stack Overflow用户

发布于 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

代码语言:javascript
复制
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
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58700668

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档