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

Bra*_*don 5 .net c# rest wcf exception

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

throw new WebFaultException<string>("Error Message", HttpStatusCode.BadRequest);
Run Code Online (Sandbox Code Playgroud)

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

我可以将针对错误请求的HTTP状态代码设置为400的唯一方法是执行以下操作:

WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
Run Code Online (Sandbox Code Playgroud)

我仍然无法获取异常以JSON形式返回。

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

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

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

小智 4

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

<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" />
Run Code Online (Sandbox Code Playgroud)

将响应格式设置为 json (您已经完成了)

[WebGet(UriTemplate = "", ResponseFormat = WebMessageFormat.Json)]
Run Code Online (Sandbox Code Playgroud)