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;
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With