我正在使用 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")]
有没有简单的方法可以做到这一点?
最佳答案
在您的 web.config 中将 AutomaticFormatSelectionEnabled 的值设置为 false
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" />
将响应格式设置为 json(您已经完成)
[WebGet(UriTemplate = "", ResponseFormat = WebMessageFormat.Json)]
关于c# - WCF 4.0 - 使用 REST 服务模板返回 JSON WebFaultException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6258545/