Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a url is reachable - Help in optimizing a Class

Tags:

c#

uri

asp.net

net 4 and c#.

I need a Class able to return a Bool value if an Uri (string) return HTTP status codes 200.

At the moment I have this code (it work using try to see if it is possible connect to the Uri) but I would like implemented with "HttpStatusCode.OK" instead.

  • Do you know a better approach?

Thanks.

public static bool IsReachableUri(string uriInput)
        {
            // Variable to Return
            bool testStatus;
            // Create a request for the URL.
            WebRequest request = WebRequest.Create(uriInput);
            request.Timeout = 15000; // 15 Sec

            WebResponse response;
            try
            {
                response = request.GetResponse();
                testStatus = true; // Uri does exist                 
                response.Close();
            }
            catch (Exception)
            {
                testStatus = false; // Uri does not exist
            }
            // Result
            return testStatus;
        }
like image 514
GibboK Avatar asked Mar 21 '11 13:03

GibboK


People also ask

How do you check if a website is optimized?

The 'Basic SEO' tab will tell you how well your content is optimized for common SEO guidelines. The 'Title' tab will tell you how well your title is optimized for the search engines. Click this tab to see how well your title is performing.

What does it mean to optimize a URL?

Website optimization is the process of using tools, advanced strategies, and experiments to improve the performance of your website, further drive more traffic, increase conversions, and grow revenue.


1 Answers

Well, firstly it would be better to have a using statement for your response instead of just calling Close - in this case there's not much difference, but in general using statements are the way to go.

As for testing the result status - just cast the response to HttpWebResponse and then use the StatusCode property. Something like this:

HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.Timeout = 15000;
request.Method = "HEAD"; // As per Lasse's comment
try
{
    using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
    {
        return response.StatusCode == HttpStatusCode.OK;
    }
}
catch (WebException)
{
    return false;
}
like image 177
Jon Skeet Avatar answered Oct 18 '22 19:10

Jon Skeet