3

我正在创建一个以 JSON 格式返回数据的 WCF 服务。我试图弄清楚如何最好地处理异常,并尝试使用 WebFaultException 类在响应中返回异常详细消息,稍后可以将其输出给用户。

我正在尝试的这种方法的简单测试如下

WCF 服务方法

    <WebInvoke(Method:="POST",
        ResponseFormat:=WebMessageFormat.Json)>
    <OperationContract()>
    Public Function Test() As Object
        Throw New WebFaultException(Of String)("Message Details", Net.HttpStatusCode.NotFound)
    End Function

根据我在搜索此问题的答案时的发现,您应该为服务提供一个将 includeExceptionDetailInFaults 设置为 true 的行为配置。

我的网络配置

<service name="WebserviceExceptionTest.Service" behaviorConfiguration="behavior">
    <endpoint address="" behaviorConfiguration="WebserviceExceptionTest.ServiceAspNetAjaxBehavior"
        binding="webHttpBinding" contract="WebserviceExceptionTest.Service" />
</service>

  <serviceBehaviors>
    <behavior name="behavior">
      <serviceDebug includeExceptionDetailInFaults="True"/>
    </behavior>

不幸的是,这似乎对我不起作用,响应仍然不包含异常详细信息,JSON 字符串如下所示:

{"ExceptionDetail":null,"ExceptionType":null,"Message":"Not Found","StackTrace":null}

有谁知道我做错了什么,还是我完全走错了路?谢谢!

编辑

我得到的响应始终是“500 内部服务器错误”,即使我希望它得到 400 未找到。错误消息确实包含“无内容”。

4

1 回答 1

0

将您的 automaticFormatSelectionEnabled 设置为 false,将 defaultOutgoingResponseFormat 设置为 Json(我相信它甚至会忽略 ResponseFormat:=WebMessageFormat.Json)

<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" defaultOutgoingResponseFormat ="Json" />

http://msdn.microsoft.com/en-us/library/system.servicemodel.description.webhttpendpoint.automaticformatselectionenabled.aspx

于 2013-10-02T08:39:06.323 回答