使用RESTful客户端捕获EndpointNotFoundException

时间:2015-05-27 13:24:58

标签: c# .net wcf rest exception

我实现了简单的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”或知道我的服务器何时不可用?

2 个答案:

答案 0 :(得分:1)

您是否有必要将WebRequest类用作REST客户端?如果我错了,请纠正我,但MSDN没有说这个方法会抛出你想要的异常(https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse(v=vs.110).aspx) 如果您可以使用WebRequest之外的其他类,那么我建议:

  1. 像这样使用WebChannelFactory类
  2. Uri serviceUri = new Uri(yourUriString);
    WebChannelFactory<IYourService> factory =
    new WebChannelFactory<IYourService>(serviceUri);
    IYourService proxy = factory.CreateChannel();
    proxy.MethodFromYourService();
    

    1. 手动创建代理并使其从ClientBase类继承,如下所示:
    2.  public class ClientClass :ClientBase<IYourService>,IYourService
          {
              public string SampleGet()
              {
                 return base.Channel.SampleGet();
              }
          }
      

      我已经检查过并且两种方式都给了我EndpointNotFoundException。

      EDIT。 ClientBase要求Web配置中的system.serviceModel部分正常工作。

答案 1 :(得分:0)

捕获响应代码并确定它是404还是5XX错误。每次出错时,根据响应代码引发新的异常。

我会将响应代码放入switch语句中,并根据需要执行不同的操作并为每个响应代码引发不同的异常。