如何在C#中测试与未知Web服务的连接?

Ric*_*ACC 14 c# web-services

我正忙着写一个监视RAS连接状态的类.我需要进行测试以确保连接不仅已连接,而且还可以与我的Web服务进行通信.由于这个类将在未来的许多项目中使用,我想要一种方法来测试与webservice的连接,而不需要了解它.

我正在考虑将URL传递给类,以便它至少知道在哪里找到它.Ping服务器不是一个充分的测试.服务器可以使用,但服务可以脱机.

如何有效地测试我是否能够从Web服务获得响应?

Blu*_*que 16

您可以尝试以下测试网站存在的方法:

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;
}
Run Code Online (Sandbox Code Playgroud)


g .*_*g . 7

你是对的,ping服务器是不够的.服务器可能已启动,但由于多种原因,Web服务不可用.

为了监视我们的Web服务连接,我创建了一个具有方法CheckService()的IMonitoredService接口.每个Web服务的包装类实现此方法以在Web服务上调用无害方法并报告服务是否已启动.这允许监视任何数量的服务,而不需要知道服务细节的负责监视的代码.

如果您对Web服务直接访问URL所返回的内容有所了解,您可以尝试使用该URL.例如,Microsoft的asmx文件返回Web服务的摘要.其他实现可能表现不同.