WCF 4.0-使用REST服务模板返回JSON WebFaultException

本文关键字:返回 JSON WebFaultException 服务 使用 REST WCF | 更新日期: 2023-09-27 17:58:36

我正在使用WCF REST服务模板40(CS)。我抛出的WebFaultException如下:

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")]

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

WCF 4.0-使用REST服务模板返回JSON WebFaultException

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

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

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

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

WebHttpBehavior.FaultExceptionEnabled设置为true时,无论automaticFormatSelectionEnabled配置设置或响应格式属性设置如何,WebFaultException都将导致200响应,其中故障呈现为XML而不是JSON。MSDN文档中没有提到这一点,并且具有误导性,因为它指出该属性仅与500响应代码有关。

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

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