WCF 4.0 - Return JSON WebFaultException Using REST Service Template

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

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

However, when I test this with my client, everything returns as an Http 500 status code and the response is XML. I see an error message in the XML response. When I make the call correctly, I get a 200 response, and the answer is in JSON, which is correct, given the configuration of my configuration and ServiceContract.

The only way I can get the HTTP status code: 400 for Bad Request is to do this:

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

I still cannot get an exception to return as JSON.

Edit Adding a signature for more information:

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

Is there an easy way to do this?

+4
source share
3 answers

In your web.config, set AutomaticFormatSelectionEnabled to false

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

Set json response format (which you already made)

 [WebGet(UriTemplate = "", ResponseFormat = WebMessageFormat.Json)] 
+4
source

If the WebHttpBehavior.FaultExceptionEnabled parameter WebHttpBehavior.FaultExceptionEnabled set to true , the WebFaultException will result in a 200 response with an error displayed as XML, not JSON, despite the setting of the automaticFormatSelectionEnabled configuration attribute or response format settings. The MSDN documentation does not mention this and is misleading in stating that this property is associated only with a 500 response code.

+4
source

for those who still have this problem. It 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); 
0
source

All Articles