WCF 4.0 – 使用REST服务模板返回JSON WebFaultException
我正在使用WCF REST服务模板40(CS)。 我正在抛出WebFaultExceptions:
throw new WebFaultException("Error Message", HttpStatusCode.BadRequest);
但是,当我使用我的客户端测试时,所有内容都以Http状态代码500返回,响应为XML。 我可以在XML响应中看到错误消息。 当我正确拨打电话时,我得到200响应并且响应是JSON,这是正确的,因为我的配置和ServiceContract的设置方式。
我可以将错误请求的HTTP状态代码设置为400的唯一方法是:
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
我仍然无法获得以JSON身份返回的exception。
编辑添加签名以获取更多信息:
[OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json, UriTemplate = "myendpoint")]
有一个简单的方法来实现这一目标吗?
在web.config中,将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( new Response(false,"was not found", ""),System.Net.HttpStatusCode.BadRequest);