【问题标题】:WCF 4.0 - Returning JSON WebFaultException with REST Service TemplateWCF 4.0 - 使用 REST 服务模板返回 JSON WebFaultException
【发布时间】:2011-09-09 15:43:07
【问题描述】:

我正在使用 WCF REST 服务模板 40(CS)。我这样抛出 WebFaultExceptions:

throw new WebFaultException<string>("Error Message", HttpStatusCode.BadRequest);

但是,当我用我的客户端对此进行测试时,所有内容都作为 500 的 Http 状态代码返回,并且响应是 XML。我可以在 XML 响应中看到错误消息。当我正确拨打电话时,我会收到 200 响应,并且响应采用 JSON 格式,考虑到我的配置和 ServiceContract 的设置方式,这是正确的。

我可以让错误请求的 HTTP 状态代码为 400 的唯一方法是这样做:

WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;

我仍然无法让异常返回为 JSON。

编辑添加签名以获取更多信息:

[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json, UriTemplate = "myendpoint")]

有没有简单的方法可以做到这一点?

【问题讨论】:

  • 如果这工作正常,状态码应该是 400(错误请求)。您能否启用跟踪以查看是否有其他原因阻止 WebFaultException 被处理?我刚刚使用 REST 服务模板创建了一个新项目,将 (ResponseFormat = WebMessageFormat.Json) 添加到其中一个操作中,并添加了您所拥有的同一行 - 响应返回编码为 JSON,而不是 XML。
  • 可能是我在我的代码中这样做:catch(WebFaultException&lt;string&gt; ex) { throw; } 吗?如果需要,我还可以添加其他配置信息。
  • 这应该不是问题;能否贴出操作合约的签名(带有[WebGet/WebInvoke]属性)?
  • 我添加了我的方法签名。它们都是 POST 并且具有类似的设置。

标签: c# .net wcf exception rest


【解决方案1】:

在您的 web.config 中,将 AutomaticFormatSelectionEnabled 的值设置为 false

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

将响应格式设置为 json(您已经这样做了)

[WebGet(UriTemplate = "", ResponseFormat = WebMessageFormat.Json)]

【讨论】:

    【解决方案2】:

    WebHttpBehavior.FaultExceptionEnabled 设置为true 时,WebFaultException 将产生一个 200 响应,并将错误呈现为 XML 而不是 JSON,尽管有 automaticFormatSelectionEnabled 配置设置或响应格式属性设置。 MSDN 文档没有提及这一点,并且具有误导性,因为它声明此属性仅与 500 响应代码相关。

    【讨论】:

    • WebHttpBehavior.FaultExceptionEnabled 设置为false 对我有帮助。否则,我总是会在每次抛出 WebFaultException 时得到 500 响应代码。
    【解决方案3】:

    对于那些仍然有这个问题的人。这对我有用

    WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
    throw new System.ServiceModel.Web.WebFaultException<Response>(
              new Response(false,"was not found", ""),System.Net.HttpStatusCode.BadRequest);
    

    【讨论】:

    • 什么是Response
    猜你喜欢
    • 2013-01-21
    • 2011-09-13
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 1970-01-01
    相关资源
    最近更新 更多