How to process WebResponse when .NET throws WebException ((400) Bad Request)? How to process WebResponse when .NET throws WebException ((400) Bad Request)? asp.net asp.net

How to process WebResponse when .NET throws WebException ((400) Bad Request)?


Using a try/catch block like this and processing the error message appropriately should work fine:

    var request = (HttpWebRequest)WebRequest.Create(address);    try {        using (var response = request.GetResponse() as HttpWebResponse) {            if (request.HaveResponse && response != null) {                using (var reader = new StreamReader(response.GetResponseStream())) {                    string result = reader.ReadToEnd();                }            }        }    }    catch (WebException wex) {        if (wex.Response != null) {            using (var errorResponse = (HttpWebResponse)wex.Response) {                using (var reader = new StreamReader(errorResponse.GetResponseStream())) {                    string error = reader.ReadToEnd();                    //TODO: use JSON.net to parse this string and look at the error message                }            }        }    }}

However, using the Facebook C# SDK makes this all really easy so that you don't have to process this yourself.


The WebException still has the "real" response in the Response property (assuming there was a response at all) so you can get the data from that within the catch block.