Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WebException如何用一个主体获得完整的响应?_C#_Webexception - Fatal编程技术网

C# WebException如何用一个主体获得完整的响应?

C# WebException如何用一个主体获得完整的响应?,c#,webexception,C#,Webexception,在WebException中,我看不到GetResponse的主体。这是我的C语言代码: 我看到了头球,但没有看到身体。这是Wireshark针对请求的输出: POST /api/1.0/authentication.json HTTP/1.1 Content-Type: application/x-www-form-urlencoded Accept: application/json Host: nbm21tm1.teamlab.com Content-Len

在WebException中,我看不到GetResponse的主体。这是我的C语言代码:

我看到了头球,但没有看到身体。这是Wireshark针对请求的输出:

POST /api/1.0/authentication.json HTTP/1.1    
Content-Type: application/x-www-form-urlencoded    
Accept: application/json    
Host: nbm21tm1.teamlab.com    
Content-Length: 49    
Connection: Keep-Alive    

userName=XXX&password=YYYHTTP/1.1 500 Server error    
Cache-Control: private, max-age=0    
Content-Length: 106    
Content-Type: application/json; charset=UTF-8    
Server: Microsoft-IIS/7.5    
X-AspNet-Version: 2.0.50727    
X-Powered-By: ASP.NET    
X-Powered-By: ARR/2.5

Date: Mon, 06 Aug 2012 12:49:41 GMT    
Connection: close    

{"count":0,"startIndex":0,"status":1,"statusCode":500,"error":{"message":"Invalid username or password."}}
是否有可能在WebException中看到消息文本?
谢谢。

这只是对现有答案的改进。我编写了一种方法,通过增强消息处理抛出/重新抛出的细节,其中包括响应正文:

var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();

dynamic obj = JsonConvert.DeserializeObject(resp);
var messageFromServer = obj.error.message;
以下是我的代码(在Client.cs中):


我没有看到
使用
语句的任何答案,也没有看到
异步
的任何用途

公共静态类WebExceptionExtensions
{
公共静态字符串GetResponseBy(此WebException WebException)
{
if(webException.Status==WebExceptionStatus.ProtocolError)
{
尝试
{
使用(var stream=webException.Response.GetResponseStream())
{
使用(变量读取器=新的流读取器(流))
{
字符串msg=reader.ReadToEnd();
if(string.IsNullOrEmpty(msg)&&webException.Response是HttpWebResponse)
msg=$“{response.StatusDescription}({(int)response.StatusCode})”;//如果找不到,请提供一些错误消息
返回味精;
}
}
}
catch(WebException)//我们尝试了
{
返回字符串。空;
}
}
其他的
{
返回字符串。空;
}
}
公共静态异步任务GetResponseBodyAsync(此WebException WebException)
{
if(webException.Status==WebExceptionStatus.ProtocolError)
{
尝试
{
使用(var stream=webException.Response.GetResponseStream())
{
使用(变量读取器=新的流读取器(流))
{
string msg=wait reader.ReadToEndAsync();
if(string.IsNullOrEmpty(msg)&&webException.Response是HttpWebResponse)
msg=$“{response.StatusDescription}((int){response.StatusCode})”;//如果找不到,请提供一些错误消息
返回味精;
}
}
}
catch(WebException)//我们尝试了
{
返回字符串。空;
}
}
其他的
{
返回字符串。空;
}
}
}
现在,每当我们捕获WebException时,就很容易得到响应体

试试看
{
//在这里工作。。。
}
catch(WebException-we)
{
Console.WriteLine(we.GetResponseBody());//同步
Console.WriteLine(wait we.GetResponseBodyAsync());//或异步
}
捕获(例外e)
{
抛出新异常(“发生意外错误”,e);
}

您是否尝试过(HttpWebResponse)we.Response;“we”是您捕获的WebException?要在rethrown异常中保留堆栈跟踪,请不要使用
throw-ex但只是
抛出(在默认情况下)。此外(如果需要),我会将原始WebException放入自定义异常的InnerException(通过适当的构造函数)。对于不熟悉JsonConvert的任何人,您需要从nuget package manager获取Newtonsoft.Json。请使用Kyle的解释更新答案,因为Newtonsoft.Json是optionall。此外,请解释此代码应该在Try-Catch代码块的Catch fallback子句中,请求应该在该代码块中。我知道在这种情况下,对于专注的读者和@iwtu来说,这是显而易见的,但全面的答案可以让初学者真正了解这个答案;)StreamReader实现IDisposable,所以将其封装在using语句中不是最佳做法吗?快速查看StreamReader的Dispose方法表明它在其中进行了一些重要的清理。@sammy34不用担心,因为这里没有非托管代码/数据,所以垃圾收集器可以轻松地处理它。。。(但使用始终是一个好习惯)
var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();

dynamic obj = JsonConvert.DeserializeObject(resp);
var messageFromServer = obj.error.message;
try {
 WebClient client = new WebClient();
 client.Encoding = Encoding.UTF8;
 string content = client.DownloadString("https://sandiegodata.atlassian.net/wiki/pages/doaddcomment.action?pageId=524365");
 Console.WriteLine(content);
 Console.ReadKey();
} catch (WebException ex) {
 var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
 Console.WriteLine(resp);
 Console.ReadKey();
}
/// <summary>
///     Tries to rethrow the WebException with the data from the body included, if possible. 
///     Otherwise just rethrows the original message.
/// </summary>
/// <param name="wex">The web exception.</param>
/// <exception cref="WebException"></exception>
/// <remarks>
///     By default, on protocol errors, the body is not included in web exceptions. 
///     This solutions includes potentially relevant information for resolving the
///     issue.
/// </remarks>
private void ThrowWithBody(WebException wex) {
    if (wex.Status == WebExceptionStatus.ProtocolError) {
        string responseBody;
        try {
            //Get the message body for rethrow with body included
            responseBody = new StreamReader(wex.Response.GetResponseStream()).ReadToEnd();

        } catch (Exception) {
            //In case of failure to get the body just rethrow the original web exception.
            throw wex;
        }

        //include the body in the message
        throw new WebException(wex.Message + $" Response body: '{responseBody}'", wex, wex.Status, wex.Response);
    }

    //In case of non-protocol errors no body is available anyway, so just rethrow the original web exception.
    throw wex;
}
//Execute Request, catch the exception to eventually get the body
try {
    //GetResponse....
    }
} catch (WebException wex) {
    if (wex.Status == WebExceptionStatus.ProtocolError) {
        ThrowWithBody(wex);
    }

    //otherwise rethrow anyway
    throw;
}