我正在尝试使用此链接中给出的逻辑来获取Web服务的状态 webservice status
try
{
var myRequest = (HttpWebRequest)WebRequest.Create(url);
NetworkCredential networkCredential = new NetworkCredential("UserName", "password","domain");
// Associate the 'NetworkCredential' object with the 'WebRequest' object.
myRequest.Credentials = networkCredential;
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
MessageBox.Show(string.Format("{0} Available", url));
}
else
{
// well, at least it returned...
MessageBox.Show(string.Format("{0} Returned, but with status: {1}", url, response.StatusDescription));
}
}
catch (Exception ex)
{
// not available at all, for some reason
MessageBox.Show(string.Format("{0} unavailable: {1}", url, ex.Message));
}
但我面临的问题是,当服务返回200以外的HTTPStatus代码时,代码会转到异常块。
如果我有10个Web服务的列表,如果我正在运行foreach循环并为每个URL执行此代码,并且由于我的第3 /第4服务的某些原因返回500,代码将进入异常块并返回并且错误。
请建议我如何克服这一点。
由于