我实现了简单的RestFull客户端:
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception(String.Format("Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription));
}
StreamReader streamReader = new StreamReader(response.GetResponseStream());
string responseData = streamReader.ReadToEnd();
return responseData;
} 这个例子运行得很好,但是当我的服务不可用时,我想捕捉"EndpointNotFoundException“。现在我抓到System.Net.WebException了。
下面这行:
request.GetResponse()是根据.NET规范落下的线和抛出的线:
System.InvalidOperationException:
System.Net.ProtocolViolationException:
System.NotSupportedException:
System.Net.WebException:我如何重构我的RestFull客户端来捕获"EndpointNotFoundException“或者知道我的服务器何时不可用?
发布于 2015-05-28 00:03:56
这对你使用WebRequest类作为REST客户端有必要吗?如果我错了,请纠正我,但MSDN没有说这个方法抛出了你想要的异常(https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse(v=vs.110).aspx如果你可以使用WebRequest以外的类,那么我建议:
使用WebChannelFactory类的
Uri serviceUri = new Uri(yourUriString);
WebChannelFactory<IYourService> factory =
new WebChannelFactory<IYourService>(serviceUri);
IYourService proxy = factory.CreateChannel();
proxy.MethodFromYourService();或
public class ClientClass :ClientBase<IYourService>,IYourService
{
public string SampleGet()
{
return base.Channel.SampleGet();
}
}我已经检查过了,两种方法都给了我EndpointNotFoundException。
编辑。ClientBase需要web配置中的system.serviceModel部分才能正常工作。
发布于 2015-05-28 03:00:17
捕获响应码并确定它是404还是5XX错误。每次出现错误时,根据响应代码引发新的异常。
我会将响应代码放入switch语句中,并在需要时为每个响应代码执行不同的操作并引发不同的异常。
https://stackoverflow.com/questions/30483850
复制相似问题