WCF RESTFul服务中的异常处理

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WCF RESTFul服务中的异常处理相关的知识,希望对你有一定的参考价值。

我正在使用WCF服务4.5 F / W开发REST Full API。请建议如何向客户端发送异常或任何业务验证消息。我正在寻找非常通用的解决方案,请提出最佳方法。我尝试了下面的一些方法,

  1. 在向客户端发送响应之前设置OutgoingWebResponseContext。
  2. 定义的故障合同只能正常工作添加服务引用(代理类)不能在REST FULL环境中工作。
  3. 在catch块中添加WebFaultException类。
  4. WCF休息入门套件 - 我收到了一些关于此的文章和帖子,但他们的codeplex官方建议不再提供此信息。 link。所以,我不想这样做。

这些没有按预期工作..我的示例代码片段:接口:

    [OperationContract]
    [FaultContract(typeof(MyExceptionContainer))]
    [WebInvoke(Method = "GET", UriTemplate = "/Multiply/{num1}/{num2}", BodyStyle = WebMessageBodyStyle.Wrapped,RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
    string Multiply(string num1, string num2);

执行:

         public string Multiply(string num1, string num2)
    {
        if (num1 == "0" || num2 == "0")
        {
            try
            {
                MyExceptionContainer exceptionDetails = new MyExceptionContainer();
                exceptionDetails.Messsage = "Business Rule violatuion";
                exceptionDetails.Description = "The numbers should be non zero to perform this operation";
                //OutgoingWebResponseContext outgoingWebResponseContext = WebOperationContext.Current.OutgoingResponse;
                //outgoingWebResponseContext.StatusCode = System.Net.HttpStatusCode.ExpectationFailed;
                //outgoingWebResponseContext.StatusDescription = exceptionDetails.Description.ToString();
               // throw new WebFaultException<MyExceptionContainer>(exceptionDetails,System.Net.HttpStatusCode.Gone);
                throw new FaultException<MyExceptionContainer>(exceptionDetails,new FaultReason("FaultReason is " + exceptionDetails.Messsage + " - " + exceptionDetails.Description));
            }
            catch (Exception ex)
            {
                throw new FaultException(ex.Message);
            }
        }

        return Convert.ToString(Int32.Parse(num1) * Int32.Parse(num2));
    }

Web.Config:

  <system.serviceModel>
<services>
  <service name="TestService.TestServiceImplementation" behaviorConfiguration="ServiceBehaviour">
    <endpoint binding="webHttpBinding" contract="TestService.ITestService" behaviorConfiguration="webHttp" >
    </endpoint>
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehaviour">
      <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
      <serviceMetadata httpGetEnabled="true"/>
      <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="webHttp" >
      <webHttp helpEnabled="true" faultExceptionEnabled="true"/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

客户:

try
        {
            string serviceUrl = "http://localhost:51775/TestService.cs.svc/Multiply/0/0";
            //Web Client
            //WebClient webClient = new WebClient();
            //string responseString = webClient.DownloadString(serviceUrl);
            WebRequest req = WebRequest.Create(serviceUrl);
            req.Method = "GET";
            req.ContentType = @"application/xml; charset=utf-8";
            HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
            if (resp.StatusCode == HttpStatusCode.OK)
            {
                XmlDocument myXMLDocument = new XmlDocument();
                XmlReader myXMLReader = new XmlTextReader(resp.GetResponseStream());
                myXMLDocument.Load(myXMLReader);
                Console.WriteLine(myXMLDocument.InnerText);
            }
            Console.ReadKey();
        }
        catch (Exception ex)
        { 
        Console.WriteLine(ex.Message);
        }

这是我的第一个问题,感谢所有充满激情的开发人员......!

以上是关于WCF RESTFul服务中的异常处理的主要内容,如果未能解决你的问题,请参考以下文章

带有 Restful API 和循环引用问题的 WCF 服务

WCF REST 完整服务中的异常处理

WCF Restful Web 服务客户端限制

WCF Restful返回HttpResponseMessage想要在设置内容时进行协商

使用 WCF/RESTful 服务的 Android 应用程序

WCF Restful 服务 IIS 错误