【问题标题】:Error Handling in WCF WebHttp Services with WebFaultException only xml formated exceptionWCF WebHttp 服务中的错误处理与 WebFaultException 仅 xml 格式的异常
【发布时间】:2011-11-17 12:37:55
【问题描述】:

我试图让 WebFaultException 以 json 和 xml 的形式返回,具体取决于

中所述的客户端要求的内容

http://blogs.msdn.com/b/endpoint/archive/2010/01/21/error-handling-in-wcf-webhttp-services-with-webfaultexception.aspx

我的服务界面是这样的

    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "session_record?id={id}&command={command}")]
    void SessionRecord(Guid id, String command);

例外

throw new WebFaultException<string>("Session not started", HttpStatusCode.Conflict);

Web.config 服务设置

<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<behaviors>
  <serviceBehaviors>
    <behavior>
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<standardEndpoints>
  <webHttpEndpoint>
    <standardEndpoint name="" helpEnabled="true" faultExceptionEnabled="true" automaticFormatSelectionEnabled="true"  />
  </webHttpEndpoint>
</standardEndpoints>

我的客户调用服务

$.ajax({
            url: "Webservice/session_record?id={id}&command={command}".format({ id: $("#sessionGuid").val(), command : "start" }),
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                alert("Started");
            }
        });

除了从服务器接收 json,我会得到 xml

当我在我发布的链接中读到它时,我应该是可能的

使用 WebFaultException,在响应消息正文中序列化的异常详细信息将始终采用客户端在没有错误时会收到的格式(XML 或 JSON)。如果客户端期待 XML,客户端将 > 获取序列化为 XML 的异常详细信息。同样,如果客户端期待 JSON,>客户端将获取序列化为 JSON 的异常详细信息。

【问题讨论】:

  • 发现解决方案 faultExceptionEnabled 需要为 false,现在我在 json 中得到了异常

标签: c# .net wcf json exception-handling


【解决方案1】:

我找到了解决办法; faultExceptionEnabled 必须为 false。现在我在 json 中得到了异常。

【讨论】:

  • 我还需要将 helpEnabled 设置为 false 才能正常工作,否则 WebFaultException 只会被 WCF 吞没,它会返回状态码为 400 的标准帮助消息。
【解决方案2】:

Web.config 服务设置中的微小更改也应该可以工作: automaticFormatSelectionEnabled="false" defaultOutgoingResponseFormat="json"

<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<behaviors>
  <serviceBehaviors>
    <behavior>
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<standardEndpoints>
  <webHttpEndpoint>
    <standardEndpoint name="" helpEnabled="true" faultExceptionEnabled="true" automaticFormatSelectionEnabled="false" defaultOutgoingResponseFormat="Json" />
  </webHttpEndpoint>
</standardEndpoints>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多