WCF WebHttp服务中WebFaultException仅xml格式异常的错误处理

本文关键字:异常 格式 错误 处理 xml WebHttp 服务 WebFaultException WCF | 更新日期: 2023-09-27 18:15:04

我试图让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);

网络。配置服务设置

<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的异常详细信息。

WCF WebHttp服务中WebFaultException仅xml格式异常的错误处理

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

网页的小改动。配置服务设置也应该工作: 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>