我正在启动 HttpWebRequest,然后检索它的响应。有时,我会收到 500(或至少 5##)错误,但没有描述。我可以控制两个端点,并希望接收端获得更多信息。例如,我想将异常消息从服务器传递到客户端。使用 HttpWebRequest 和 HttpWebResponse 可以吗?
Code:
try
{
HttpWebRequest webRequest = HttpWebRequest.Create(URL) as HttpWebRequest;
webRequest.Method = WebRequestMethods.Http.Get;
webRequest.Credentials = new NetworkCredential(Username, Password);
webRequest.ContentType = "application/x-www-form-urlencoded";
using(HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse)
{
if(response.StatusCode == HttpStatusCode.OK)
{
// Do stuff with response.GetResponseStream();
}
}
}
catch(Exception ex)
{
ShowError(ex);
// if the server returns a 500 error than the webRequest.GetResponse() method
// throws an exception and all I get is "The remote server returned an error: (500)."
}
任何对此的帮助将不胜感激。
使用 HttpWebRequest 和 HttpWebResponse 可以吗?
您可以让 Web 服务器简单地捕获异常文本并将其写入响应正文中,然后将状态代码设置为 500。现在,客户端在遇到 500 错误时会抛出异常,但您可以读取响应流并获取异常的消息。
所以你可以抓住一个Web异常 http://msdn.microsoft.com/en-us/library/system.net.webexception.aspx如果从服务器返回非 200 状态代码并读取其正文,将会抛出以下异常:
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
catch (Exception ex)
{
// Something more serious happened
// like for example you don't have network access
// we cannot talk about a server exception here as
// the server probably was never reached
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)