c# - WCF WebHttp 服务中的错误处理,仅带有 WebFaultException xml 格式的异常

标签 c# .net wcf json exception

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

当我在我发布的链接中阅读它时,我应该可以

With the WebFaultException, the detail of the exception that is serialized in the body of >the response message will always be in the format (XML or JSON) that the client would have >received had there not been an error. If the client was expecting XML, the client will >get the exception detail serialized as XML. Likewise, if the client was expecting JSON, >the client will get the exception detail serialized as JSON.

最佳答案

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

关于c# - WCF WebHttp 服务中的错误处理,仅带有 WebFaultException xml 格式的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8167202/

相关文章:

c# - 为什么我的 SignalR 应用有时会断开连接

c# - 如何在运行时确定 C# 中 WPF 控件的边界?

.net - 在将输入字符添加到文本之前将其交换到 WPF 文本框

c# - 代码契约和类型转换

.net - 用于 .NET 的轻量级 x86 模拟器/在托管环境中执行 x86 代码

c# - 如何在没有 svcutil.exe 的情况下使用 WCF 服务?

c# - 使用 .NET 远程读取事件日志

wcf - 将 WCF 时钟偏差增加到一个多小时的实际安全后果

c# - 请提供引用/指导以制作用于管理所有 IT Assets /设备的 Web 应用程序

c# - 使用 Linq 对字典进行分组