How to retrieve content passed back from remote server when the server reponds with a System.Net.WebException 422
I am working wit开发者_JS百科h an api that also returns a valid xml string containing the error that was encountered on their system.
<?xml version="1.0" encoding="UTF-8"?>
<error>
<request>Request made to server</request>
<message>No user found for account 12345</message>
</error>
Is there any way to get that xml from the remote server out of the System.Net.WebException object? Thanks in advance :)
Direct from the MSDN docs:
When WebException is thrown by a descendant of the WebRequest class, the Response property provides the Internet response to the application.
So if you are if you are getting the exception while reading the response, you should just be able to read the Response property to get the XML contents.
Sure ya can! Just need to throw a try-catch around your request.GetResponse(), catch a WebException and read from the exceptions Response property.
WebRequest request = WebRequest.Create("http://www.google.com/ohnoa404");
WebResponse response;
try
{
response = request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response;
}
String responseString = String.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseString = reader.ReadToEnd();
}
精彩评论