I’m doing what is usually a simple http post on windows phone 7 (code below). When I look at fiddler during the post I see this result from the server
HTTP/1.1 500 Internal Server Error Cache-Control: private
Content-Type: application/json; charset=utf-8 Server:
Microsoft-IIS/7.5 jsonerror: true X-AspNet-Version: 2.0.50727
X-Server: www03 X-Site: prod Date: Tue, 16 Aug 2011 03:49:51 GMT
Content-Length: 220{“Message”:”We’re sorry … }
When I put a try catch over the async post I can’t find anything other than
{System.Net.WebException: The remote server returned an error:
NotFound. —> System.Net.WebException: The remote server returned an
error: NotFoun…
My question is this: how can I get the actual message (shown in fiddler) from this exception? or how can I avoid this exception altogether and get the json back so I can parse it for the actual error message?
Thank you in advance
public void Checkout(ResponseAndCookies responseAndCookies)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/checkout");
request.ContentType = "application/json";
request.CookieContainer = responseAndCookies.CookieContainer;
request.Method = "POST";
request.AllowAutoRedirect = false;
request.Accept = "application/json";
request.BeginGetRequestStream(new AsyncCallback(GetRequest), request);
}
private void GetRequest(IAsyncResult asyncResult)
{
var json = "{\"valid\":true}";
byte[] byteArray = Encoding.UTF8.GetBytes(json);
HttpWebRequest request = (HttpWebRequest) asyncResult.AsyncState;
Stream newStream = request.EndGetRequestStream(asyncResult);
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponse), request);
}
private void GetResponse(IAsyncResult asyncResult)
{
var response = ReadResponse(asyncResult); //if I try catch this I get the exception listed above :(
}
private ResponseAndCookies ReadResponse(IAsyncResult result)
{
Stream dataStream = null;
HttpWebRequest request = (HttpWebRequest) result.AsyncState;
HttpWebResponse response = request.EndGetResponse(result) as HttpWebResponse;
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
var responseAndCookies = new ResponseAndCookies
{CookieContainer = request.CookieContainer, Markup = responseFromServer};
return responseAndCookies;
}
HTTP 500 isn’t the same as “Not Found” (that would be HTTP 404). So your exception isn’t actually related. Anyway, you obviously need to read the content response stream.
You can read the response using the WebException.Response property, inside your catch clause.
When that’s said, I would recommend you to look into a framework like RestSharp. No point writing so much code yourself.