Search code examples
c#.nethttpwebrequest

HttpWebRequest accept 500 Internal Server Error


This is my code:

HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;

WebResponse wr = req.GetResponse();

When the server returns 500 Internal Server Error, exception is thrown in req.GetResponse(). I would like the GetResponse() to accept this Response Code, it is normal for the passed url to throw this Response Code. I would like to parse the Html despite Response Code 500 Internal Server Error. Is it possible to say to GetResponse() method not to verify the Response Code?


Solution

  • try
    {
        HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
    
        WebResponse wr = req.GetResponse();
    }
    catch (WebException wex)
    {
        var pageContent = new StreamReader(wex.Response.GetResponseStream())
                              .ReadToEnd();
    }