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

LCJ*_*LCJ 17 .net c# asp.net wcf web-services

我需要创建一个C#应用程序,它将监视一组Web服务是否已启动并正在运行.用户将从下拉列表中选择服务名称.该程序需要使用相应的服务URL进行测试,并显示该服务是否正在运行.最好的方法是什么?我想到的一种方法是测试我们是否能够下载wsdl.有没有更好的办法?

注意:此应用程序的目的是用户只需要知道服务名称.他不需要记住/存储服务的相应URL.

我需要一个网站版本和这个C#应用程序的桌面应用程序版本.

注意:现有服务正在使用WCF.但是将来可能会添加非WCF服务.

注意:我的程序不会知道(或不感兴趣)服务中的操作.所以我无法调用服务操作.

参考

  1. 如何在不使用ping的情况下检查Web服务是否已启动并运行?
  2. C程序 - 如何检查Web服务是否正在运行

pau*_*aul 35

这不保证功能,但至少你可以检查到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));
}
Run Code Online (Sandbox Code Playgroud)

  • 有没有其他方法可以检查进程是否已启动并正在运行?我正在尝试你的建议`GetResponse()` 方法,但它需要更多的时间.. (2认同)
  • 这是我获取服务uri的方法:`var url = ServiceClient()。Endpoint.Address.Uri;` (2认同)

小智 6

I may be too late with the answer but this approach works for me. I used Socket to check if the process can connect. HttpWebRequest works if you try to check the connection 1-3 times but if you have a process which will run 24hours and from time to time needs to check the webserver availability that will not work anymore because will throw TimeOut Exception.

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                var result = socket.BeginConnect("xxx.com", 80, null, null);
                bool success = result.AsyncWaitHandle.WaitOne(3000,false); // test the connection for 3 seconds
                var resturnVal = socket.Connected;
                if (socket.Connected)
                    socket.Disconnect(true);
                socket.Dispose();
                return resturnVal;
Run Code Online (Sandbox Code Playgroud)

  • 我将此答案用于我的解决方案,运行良好且简洁。然而,由于 Socket 是一次性的,我将整个代码块包装在一个 `using` 块中。即:`using(Socket socket = new Socket(...)){ ... }` (4认同)