【发布时间】:2013-02-20 15:31:59
【问题描述】:
我使用 MVC4 Web API 创建了一个 RESTful Web 服务。如果出现问题,我将抛出 WebException。
throw new WebException("Account not found");
这是处理异常的客户端代码:
private void webClientPost_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
if (e.Error == null)
{
// Display result
textBoxResult.Text = e.Result;
}
else
{
// Display status code
if (e.Error is WebException)
{
StringBuilder displayMessage = new StringBuilder();
WebException we = (WebException)e.Error;
HttpWebResponse webResponse = (System.Net.HttpWebResponse)we.Response;
displayMessage.AppendLine(webResponse.StatusDescription);
// Gets the stream associated with the response.
Stream receiveStream = webResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, encode);
displayMessage.Append(readStream.ReadToEnd());
readStream.Close();
textBoxResult.Text = displayMessage.ToString();
}
}
}
catch (Exception ex)
{
textBoxResult.Text = ex.Message;
}
}
如您所见,客户端代码正在显示 WebException 中包含的 HttpWebResponse。但是显示的是:
Internal Server Error {"Message":"An error has occurred."}
这不是我的错误信息 :-( 所以我想我会使用 Mircosoft MSDN WebException 4th Constructor 指定的 WebException 的替代构造函数
在 MSDN 示例中,他们通过以下方式创建 WebResponse:
MemoryStream memoryStream = new MemoryStream(recvBytes);
getStream = (Stream) memoryStream;
// Create a 'WebResponse' object
WebResponse myWebResponse = (WebResponse) new HttpConnect(getStream);
Exception myException = new Exception("File Not found");
// Throw the 'WebException' object with a message string, message status,InnerException and WebResponse
throw new WebException("The Requested page is not found.", myException, WebExceptionStatus.ProtocolError, myWebResponse);
但是 .Net Framework 中不存在 HttpConnect :-(.
有谁知道如何使用特定的 WebResponse 创建 WebException? 谢谢, 马特
【问题讨论】:
标签: .net asp.net-mvc-4 asp.net-web-api httpwebresponse system.net.webexception