转载:http://www.cnblogs.com/xienb/p/3443282.html
winform客户端经常需要调用webservice或者WCF进行数据交互,但是远程服务有可能不存在或者服务器不可用,客户端只能通过超时或者捕获到异常感知服务不可用。其实有一个COM借口可用快速的检测检测将要调用服务的状态。右键引用COM组件:Microsoft XML,v3.0,代码如下:
string url = "http://127.0.0.1/MySrv/MsgService.svc"; XMLHTTP http = new XMLHTTP(); try { http.open("GET", url, false, null, null); http.send(url); int status = http.status; if (status == 200) { Console.WriteLine("成功"); } else { Console.WriteLine("不可用status:"+status.ToString()); } } catch { Console.WriteLine("不可用"); }
方法二:
/// <summary> /// 检查WebService是否可用 /// </summary> /// <param name="url"></param> /// <returns></returns> private static bool CheckActiveWebService(string url) { try { string uri = url + "?wsdl"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.UseDefaultCredentials = true; request.Method = "GET"; request.Timeout = 5000; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK && response.ContentType.Substring(0, 8) == "text/xml") { return true; } else { return false; } } catch (WebException e) { System.Diagnostics.Trace.Write(e.Message); return false; } }