How do you create a WebException with a custom WebResponse
.net, asp.net-mvc-4, asp.net-web-api, httpwebresponse, system.net.webexception
Solution
I am throwing a WebException if something is wrong
Oh no, don't. If something gets wrong in your Web API set the corresponding response status code.
For example:
public HttpResponseMessage Get(int id)
{
var model = this.repository.Get(id);
if (model == null)
{
return Request.CreateErrorResponse(
HttpStatusCode.NotFound,
string.Format("Sorry but we couldn't find a resource with id={0}", id)
);
}
return Request.CreateResponse(HttpStatusCode.OK, model);
}
and then on the client:
using (var client = new WebClient())
{
try
{
string result = client.DownloadString("http://example.com/api/someresources/123");
}
catch (WebException ex)
{
// get the status code:
var response = (HttpWebResponse)ex.Response;
var statusCode = response.StatusCode;
// you could also read the response stream:
using (var reader = new StreamReader(response.GetResponseStream()))
{
// now you could read the body
string body = reader.ReadToEnd();
}
}
}
Problem
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