Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore 401 unauthorized error from webrequest to get website status

I am writing an application to check the status of some internal web applications. Some of these applications use Windows authentication. When I use this code to check the status, it throws The remote server returned an error: (401) Unauthorized.. Which is understandable because I haven't provided any credentials to the webiste so I am not authorized.

WebResponse objResponse = null;
WebRequest objRequest = HttpWebRequest.Create(website);
objResponse = objRequest.GetResponse();


Is there a way to ignore the 401 error without doing something like this?

WebRequest objRequest = HttpWebRequest.Create(website);

try
{
    objResponse = objRequest.GetResponse();
}
catch (WebException ex)
{
    //Catch and ignore 401 Unauthorized errors because this means the site is up, the app just doesn't have authorization to use it.
    if (!ex.Message.Contains("The remote server returned an error: (401) Unauthorized."))
    {
        throw;
    }                    
}
like image 883
FarFigNewton Avatar asked Mar 01 '12 13:03

FarFigNewton


2 Answers

I would suggest to try this:

        try
        {
            objResponse = objRequest.GetResponse() as HttpWebResponse;
        }
        catch (WebException ex)
        {
            objResponse = ex.Response as HttpWebResponse;
        }
        finally

The WebException has the response all information you want.

like image 116
Geraldo Magella Junior Avatar answered Sep 30 '22 00:09

Geraldo Magella Junior


When the server is down or unreachable you will get a timeout exception. I know that the only way to handle that is with a try/catch.

I'm quite sure this is the case for most errors (401/404/501), so: No, you can't ignore (prevent) the exceptions but you will have to handle them. They are the only way to get most of the StatusCodes your App is looking for.

like image 24
Henk Holterman Avatar answered Sep 30 '22 01:09

Henk Holterman