Web Services C#:如何以编程方式检查Web服务是否已启动并正在运行?

wvmv3b1j  于 2022-11-15  发布在  C#
关注(0)|答案(2)|浏览(295)

我需要创建一个C#应用程序,它将监视一组Web服务是否已启动并正在运行。用户将从下拉列表中选择一个服务名称。程序需要使用相应的服务URL进行测试,并显示服务是否正在运行。最好的方法是什么?我正在考虑的一种方法是测试我们是否能够下载wsdl。有更好的方法吗?
注意:这个应用程序的目的是用户只需要知道服务名称,他不需要记住/存储服务的相应URL。
我需要这个C#应用程序的网站版本和桌面应用程序版本。
注意:现有服务正在使用WCF。但将来可能会添加非WCF服务。
注意:我的程序将不知道(或不感兴趣)服务中的操作。所以我不能调用服务操作。
参考文献

  1. How to check if a web service is up and running without using ping?
  2. C program-How do I check if a web service is running
fquxozlt

fquxozlt1#

这并不能保证功能正常,但至少可以检查到URL连接:

var url = "http://url.to.che.ck/serviceEndpoint.svc";

try
{
    var myRequest = (HttpWebRequest)WebRequest.Create(url);

    var response = (HttpWebResponse)myRequest.GetResponse();

    if (response.StatusCode == HttpStatusCode.OK)
    {
        //  it's at least in some way responsive
        //  but may be internally broken
        //  as you could find out if you called one of the methods for real
        Debug.Write(string.Format("{0} Available", url));
    }
    else
    {
        //  well, at least it returned...
        Debug.Write(string.Format("{0} Returned, but with status: {1}", 
            url, response.StatusDescription));
    }
}
catch (Exception ex)
{
    //  not available at all, for some reason
    Debug.Write(string.Format("{0} unavailable: {1}", url, ex.Message));
}
ep6jt1vc

ep6jt1vc2#

这种方法对我很有效。
我用Socket来检查进程是否可以连接。如果你尝试检查连接1-3次,HttpWebRequest就可以工作,但是如果你有一个24小时运行的进程,并且不时需要检查Web服务器的可用性,那么它就不再工作了,因为它会抛出TimeOut异常。

Socket socket 
   = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

var result = socket.BeginConnect("xxx.com", 80, null, null);

// test the connection for 3 seconds
bool success = result.AsyncWaitHandle.WaitOne(3000,false); 

var resturnVal = socket.Connected;
if (socket.Connected)
    socket.Disconnect(true);
                
socket.Dispose();
                
return resturnVal;

相关问题