I am having an issue with my variable httpRes. Basically this is the basics of a command line app that will check a set of given URL's and return their status code, i.e. unauthorized, redirect, ok etc. The problem is one of the apps within my list keeps throwing an error. So I used a try catch clause to catch the error and tell me what caused it.
Unfortunately the variable httpRes works in the try clause, but not in the catch. It keeps being returned as null. I called httpRes outside of the try/catch statement so I am hoping my scope is correct but for whatever reason the value never changes from null for the catch statement, only the try statement.
Here is the code referenced.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace URLMonitor
{
class Program
{
static void Main(string[] args)
{
string url1 = "https://google.com"; //removed internal URL for security reasons.
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url1);
httpReq.AllowAutoRedirect = false;
HttpWebResponse httpRes = null;
try
{
httpRes = (HttpWebResponse)httpReq.GetResponse();
if (httpRes.StatusCode == HttpStatusCode.OK)
{
Console.WriteLine("Website is OK");
// Close the response.
//httpRes.Close();
}
}
catch
{
if (httpRes != null)
{
if (httpRes.StatusCode == HttpStatusCode.Unauthorized)
{
Console.WriteLine("Things are not OK");
//httpRes.Close();
}
}
else
{
Console.WriteLine("Please check the URL and try again..");
//httpRes.Close();
}
}
Console.ReadLine();
}
}
}
Well if you catch an exception, that would probably be because GetResponse failed, right? So you wouldn't have assigned anything to httpRes
yet...
It seems to me that you should be catching WebException
, at which point you can look at the response - if there is one:
catch (WebException e)
{
// We're assuming that if there *is* a response, it's an HttpWebResponse
httpRes = (HttpWebResponse) e.Response;
if (httpRes != null)
{
...
}
}
It's pretty much never worth writing a bare catch
block, btw - always at least catch Exception
, but ideally catch a more specific exception type anyway, unless you're at the top level of your application stack.
Personally I wouldn't bother using the same variable for both pieces of code - I'd declare the response for the success case within the try block, and the response for the failure case in the catch block. Also note that you should normally be disposing of your WebResponse
, e.g.
using (var response = request.GetResponse())
{
// Use the response
}
I don't believe you need to do this if GetResponse
throws an exception and you obtain the response from the exception.
See more on this question at Stackoverflow