How do I test connectivity to an unknown web service in C#?

前端 未结 5 1199
鱼传尺愫
鱼传尺愫 2021-01-01 21:53

I\'m busy writing a class that monitors the status of RAS connections. I need to test to make sure that the connection is not only connected, but also that it can communica

5条回答
  •  爱一瞬间的悲伤
    2021-01-01 22:33

    You could try the following which tests the web site's existence:

    public static bool ServiceExists(
        string url, 
        bool throwExceptions, 
        out string errorMessage)
    {
        try
        {
            errorMessage = string.Empty;
    
            // try accessing the web service directly via it's URL
            HttpWebRequest request = 
                WebRequest.Create(url) as HttpWebRequest;
            request.Timeout = 30000;
    
            using (HttpWebResponse response = 
                       request.GetResponse() as HttpWebResponse)
            {
                if (response.StatusCode != HttpStatusCode.OK)
                    throw new Exception("Error locating web service");
            }
    
            // try getting the WSDL?
            // asmx lets you put "?wsdl" to make sure the URL is a web service
            // could parse and validate WSDL here
    
        }
        catch (WebException ex)
        {   
            // decompose 400- codes here if you like
            errorMessage = 
                string.Format("Error testing connection to web service at" + 
                              " \"{0}\":\r\n{1}", url, ex);
            Trace.TraceError(errorMessage);
            if (throwExceptions)
                throw new Exception(errorMessage, ex);
        }   
        catch (Exception ex)
        {
            errorMessage = 
                string.Format("Error testing connection to web service at " + 
                              "\"{0}\":\r\n{1}", url, ex);
            Trace.TraceError(errorMessage);
           if (throwExceptions)
                throw new Exception(errorMessage, ex);
            return false;
        }
    
        return true;
    }
    

提交回复
热议问题