I'm looking essentially for the same thing asked here: Any way to access response body using WebClient when the server returns an error?

But no answers have been provided so far.

The server returns a "400 bad request" status, but with a detailed error explanation as response body.

Any ideas on accessing that data with .NET WebClient? It just throws an exception when server returns an error status code.

有帮助吗?

解决方案

You cant get it from the webclient however on your WebException you can access the Response Object cast that into a HttpWebResponse object and you will be able to access the entire response object.

Please see the WebException class definition for more information.

Below is an example from MSDN (added reading the content of the web response for clarity)

using System;
using System.IO;
using System.Net;

public class Program
{
    public static void Main()
    {
        try {
            // Create a web request for an invalid site. Substitute the "invalid site" strong in the Create call with a invalid name.
            HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("invalid URL");

            // Get the associated response for the above request.
            HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();
            myHttpWebResponse.Close();
        }
        catch(WebException e) {
            Console.WriteLine("This program is expected to throw WebException on successful run."+
                              "\n\nException Message :" + e.Message);
            if(e.Status == WebExceptionStatus.ProtocolError) {
                Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
                using (StreamReader r = new StreamReader(((HttpWebResponse)e.Response).GetResponseStream()))
                {
                    Console.WriteLine("Content: {0}", r.ReadToEnd());
                }
            }
        }
        catch(Exception e) {
            Console.WriteLine(e.Message);
        }
    }
}

其他提示

You can retrieve the response content like this:

using (WebClient client = new WebClient())
{
    try
    {
        string data = client.DownloadString(
            "http://your-url.com");
        // successful...
    }
    catch (WebException ex)
    {
        // failed...
        using (StreamReader r = new StreamReader(
            ex.Response.GetResponseStream()))
        {
            string responseContent = r.ReadToEnd();
            // ... do whatever ...
        }
    }
}

Tested: on .Net 4.5.2

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top