Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# HttpWebRequest ignore HTTP 500 error

I'm trying to download a page using the WebRequest class in C#4.0. For some reason this page returns all the content correctly, but with a HTTP 500 internal error code.

Request.EndGetResponse(ar);

When the page returns HTTP 500 or 404, this method throws a WebException. How can I ignore this? I know it returns 500 but I still want to read the contents of the page / response.

like image 900
peter Avatar asked Oct 07 '10 13:10

peter


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.


2 Answers

You can a try / catch block to catch the exception and do additional processing in case of http 404 or 500 errors by looking at the response object exposed by the WebExeption class.

try
{
    response = (HttpWebResponse)Request.EndGetResponse(ar);
}
catch (System.Net.WebException ex)
{
    response = (HttpWebResponse)ex.Response;

    switch (response.StatusCode)
    {
        case HttpStatusCode.NotFound: // 404
            break;

        case HttpStatusCode.InternalServerError: // 500
            break;

        default:
            throw;
    }
}
like image 177
Martin Hyldahl Avatar answered Sep 20 '22 23:09

Martin Hyldahl


try {
    resp = rs.Request.EndGetResponse(ar);
} 
catch (WebException ex) 
{ 
    resp = ex.Response as HttpWebResponse; 
}
like image 32
peter Avatar answered Sep 17 '22 23:09

peter