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

前端 未结 5 1197
鱼传尺愫
鱼传尺愫 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:20

    If it is a Microsoft SOAP or WCF service and service discovery is allowed, you can request the web page serviceurl + "?disco" for discovery. If what is returned is a valid XML document , you know the service is alive and well. A non-Microsoft SOAP service that does not allow ?disco will probably return valid XML too.

    Sample code:

        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "?disco");
        request.ClientCertificates.Add(
          new X509Certificate2(@"c:\mycertpath\mycert.pfx", "")); // If server requires client certificate
        request.Timeout = 300000; // 5 minutes
        using (WebResponse response = request.GetResponse())
        using (Stream stream = response.GetResponseStream())
        using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
        {
          XmlDocument xd = new XmlDocument();
          xd.LoadXml(sr.ReadToEnd());
          return xd.DocumentElement.ChildNodes.Count > 0;
        }
    

    If the web server is present, but the service does not exist, an exception will be raised quickly for the 404 error. The fairly long time-out in the example is to allow a slow WCF service to restart after a long period of inactivity or after iisreset. If the client needs to be responsive, you could poll with a shorter timeout until the service is available.

提交回复
热议问题