I have created a RESTful web service using MVC4 Web API. I am throwing a WebException if something is wrong.
throw new WebException("Account not found");
Here's the client code that handles the exception:
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;
}
}
As you can see, the client code is displaying the HttpWebResponse that is contained with in the WebException. However what is displayed is:
Internal Server Error {"Message":"An error has occurred."}
This is not my error message :-( So I thought I would use an alternative constructor to the WebException as specified by Mircosoft MSDN WebException 4th Constructor
In the MSDN example, they create a WebResponse by:
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);
But the HttpConnect does not exist in the .Net Framework :-(.
Does anyone know how to create a WebException with a specific WebResponse? Thanks, Matt