0

I'm currently working on a dashboard that returns different results. One of those being the status of three websites and the current internet connection. I originally used knockout.js to ping each site but i found a better approach. For now i just use an ajax call to an mvc controller to bring back the results i require.

[HttpPost]
    public JsonResult webSiteAvailable(string url)
    {



        try
        {
            var result = false;
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
            System.Diagnostics.Stopwatch timer = new Stopwatch();
            timer.Start();

            httpReq.AllowAutoRedirect = false;
            httpReq.Proxy.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse httpRes = (HttpWebResponse)httpReq.GetResponse();
            timer.Stop();
            TimeSpan timeTaken = timer.Elapsed;

            if (httpRes.StatusCode == HttpStatusCode.NotFound)
            {
                result = false;
            }

            else
            {
                result = true;
            }


            return Json(new { status = result, code = httpRes.StatusDescription.ToString(), time = timeTaken.TotalMilliseconds.ToString() });
        }
        catch (WebException ex)
        {
            return Json(new { status = false, code = ex.Message.ToString() });
        }
        catch (Exception ex)
        {
            return Json(new { status = false, code = ex.Message.ToString() });
        }


    }

So my question is, is there a better way to test for an internet connection? I know checking to see if www.google.co.uk responds does essentially test for a connection but there must be a better way to do this. Thank you for any suggestions.

tereško
  • 58,060
  • 25
  • 98
  • 150
Tony_89
  • 797
  • 11
  • 39
  • Is this a site you access from localhost or a local network? Otherwise it's pretty much a no-brainer. Anyway, see duplicate. – CodeCaster Nov 21 '14 at 12:01
  • Does that code actually work when the url is offline? A lack of internet connection between the server and `url` will cause a timeout not a 404 and I thought `HttpWebRequest.GetResponse` threw an exception when it received a 404 anyway. – Ben Robinson Nov 21 '14 at 12:03
  • Thank you the duplicate answered my questions. And the code does work when the url is offline, and i just hand the exception and return the status code to be displayed on the dashboard. – Tony_89 Nov 21 '14 at 12:11

0 Answers0