Search code examples
asp.netexceptionhttpwebrequesthttpwebresponsesystem.net.webexception

Asp.net HttpWebResponse - how can I not depend on WebException for flow control?


I need to check whether the request will return a 500 Server Internal Error or not (so getting the error is expected). I'm doing this:

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 
request.Method = "GET";  
HttpWebResponse response = request.GetResponse() as HttpWebResponse; 

if (response.StatusCode == HttpStatusCode.OK)
     return true;
else 
    return false;

But when I get the 500 Internal Server Error, a WebException is thrown, and I don't want to depend on it to control the application flow - how can this be done?


Solution

  • Indeed, given the example at msdn, there is no way to not depend on the exception for control flow. Here's the example they give:

    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 site");
    
        // 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);
        }
    }
    catch(Exception e) {
        Console.WriteLine(e.Message);
    }
    

    Apparently, sometimes you do have to go down that route. Ah, well.