Web Service Availabilty Check

Introduction

This blog gives a simple method to check if a web service is up and connections can be made to it.
 
Overview

The below method will check if we are able to connect to a web service with the URL "url".

You can pass the web service url to the TestConnections method and the method will return success or failure.

The method uses simple HttpWebRequest and HttpWebResponse to check if the url is up.  
  1. /// <summary>  
  2. /// Checks the connection to service  
  3. /// </summary>  
  4. /// <param name="url"></param>  
  5. /// <returns></returns>  
  6. public string TestConnection(string url)  
  7. {  
  8.       try  
  9.       {  

  10.           // try accessing the web service directly via it's URL  
  11.           HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;  
  12.           request.Timeout = 30000;  

  13.           using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)  
  14.           {  
  15.                if (response.StatusCode != HttpStatusCode.OK)  
  16.                {  
  17.                      Logger.Log(LogCategory.Business, LogLevel.Warning, Constants.ConnectionFailure);  
  18.                      return Constants.ConnectionFailure;  
  19.                }  
  20.                else  
  21.                {  
  22.                      return Constants.ConnectionSuccess;  
  23.                }  
  24.          }  
  25.  
  26.         catch (WebException ex)  
  27.         {  
  28.             Logger.Log(LogCategory.App, LogLevel.Warning, string.Format(CultureInfo.InvariantCulture, "Error 
                ing connection to web service at \"{0}\":\r\n{1}", url, ex));  
  29.             throw;  
  30.         }  

  31.         catch (Exception ex)  
  32.         {  
  33.             Logger.Log(LogCategory.App, LogLevel.Warning, string.Format(CultureInfo.InvariantCulture, "Error test
  34.             ing connection to web service at \"{0}\":\r\n{1}", url, ex));  
  35.             throw;  
  36.         }  
Ebook Download
View all
Learn
View all