C#: How to programmatically check a web service is up and running?

后端 未结 2 1992
不知归路
不知归路 2020-12-09 04:04

I need to create an C# application that will monitor whether a set of web services are up and running. User will select a service name from a dropdown. The program need to

相关标签:
2条回答
  • 2020-12-09 04:31

    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;
    
    0 讨论(0)
  • 2020-12-09 04:37

    this would not guarantee functionality, but at least you could check connectivity to a 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));
    }
    
    0 讨论(0)
提交回复
热议问题