WCF 4.0 - 返回JSON WebFaultException与REST服务模板 [英] WCF 4.0 - Returning JSON WebFaultException with REST Service Template

查看:311
本文介绍了WCF 4.0 - 返回JSON WebFaultException与REST服务模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用WCF REST服务模板40(CS)。我扔WebFaultExceptions这样:

I am using the WCF REST Service Template 40(CS). I am throwing WebFaultExceptions as such:

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

然而,当我测试这个跟我的客户,一切都被返回的500 Http状态code和响应XML。我可以看到在XML响应的错误消息。当我拨打电话正确的,我得到一个200响应,响应是JSON给出的方式我的配置和的ServiceContract的设置是正确的。

However, when I test this with my client, everything is being returned as a Http Status Code of 500 and the response is XML. I can see the error message in the XML response. When I make a call correctly, I get a 200 response and the response is in JSON which is correct given the way my config and ServiceContract are setup.

我可以得到HTTP状态code为400的错误请求的唯一方法是做到这一点:

The only way I can get the HTTP Status Code to be 400 for the Bad Request is to do this:

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

我仍然不能得到异常返回的JSON。

I still cannot get the exception to return as JSON.

修改添加签名的详细信息:

Edit Adding signature for more information:

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

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

Is there an easy way to accomplish this?

推荐答案

WebHttpBehavior.FaultExceptionEnabled 设置为 WebFaultException 将导致2​​00响应与呈现为XML,而不是JSON故障,尽管 automaticFormatSelectionEnabled 配置设置或响应格式属性设置。 MSDN文档没有提到这一点,它指出,这个属性是只与500响应code被误导

When WebHttpBehavior.FaultExceptionEnabled is set to true, WebFaultException will result in a 200 response with the fault rendered as XML and not JSON, despite the automaticFormatSelectionEnabled configuration setting or response format attribute settings. The MSDN documentation does not mention this and is misleading in that it states that this property is only related to the 500 response code.

这篇关于WCF 4.0 - 返回JSON WebFaultException与REST服务模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆