WCF 4.0 - Returning JSON WebFaultException with RE

2019-03-10 11:10发布

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

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

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.

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;

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?

3条回答
Anthone
2楼-- · 2019-03-10 11:37

In you web.config set the value of AutomaticFormatSelectionEnabled to false

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

Set the response format to json (which you have done already)

[WebGet(UriTemplate = "", ResponseFormat = WebMessageFormat.Json)]
查看更多
聊天终结者
3楼-- · 2019-03-10 11:41

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.

查看更多
劳资没心,怎么记你
4楼-- · 2019-03-10 11:47

for those still having this issue. This worked for me

WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
throw new System.ServiceModel.Web.WebFaultException<Response>(
          new Response(false,"was not found", ""),System.Net.HttpStatusCode.BadRequest);
查看更多
登录 后发表回答