title: How to make custom WCF error handler return JSON response with non-OK http code?
body: <p>I'm implementing a RESTful web service using WCF and the WebHttpBinding. Currently I'm working on the error handling logic, implementing a custom error handler (IErrorHandler); the aim is to have it catch any uncaught exceptions thrown by operations and then return a JSON error object (including say an error code and error message - e.g. { "errorCode": 123, "errorMessage": "bla" }) back to the browser user along with an an HTTP code such as BadRequest, InteralServerError or whatever (anything other than 'OK' really). Here is the code I am using inside the ProvideFault method of my error handler:</p>
  
  <pre><code>fault = Message.CreateMessage(version, "", errorObject, new DataContractJsonSerializer(typeof(ErrorMessage)));
  var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
  fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
  var rmp = new HttpResponseMessageProperty();
  rmp.StatusCode = System.Net.HttpStatusCode.InternalServerError;
  rmp.Headers.Add(HttpRequestHeader.ContentType, "application/json");
  fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
  </code></pre>
  
  <p>--> This returns with Content-Type: application/json, however the status code is 'OK' instead of 'InternalServerError'.</p>
  
  <pre><code>fault = Message.CreateMessage(version, "", errorObject, new DataContractJsonSerializer(typeof(ErrorMessage)));
  var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
  fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
  var rmp = new HttpResponseMessageProperty();
  rmp.StatusCode = System.Net.HttpStatusCode.InternalServerError;
  //rmp.Headers.Add(HttpRequestHeader.ContentType, "application/json");
  fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
  </code></pre>
  
  <p>--> This returns with the correct status code, however the content-type is now XML. </p>
  
  <pre><code>fault = Message.CreateMessage(version, "", errorObject, new DataContractJsonSerializer(typeof(ErrorMessage)));
  var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
  fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
  
  var response = WebOperationContext.Current.OutgoingResponse;
  response.ContentType = "application/json";
  response.StatusCode = HttpStatusCode.InternalServerError;
  </code></pre>
  
  <p>--> This returns with the correct status code and the correct content-type! The problem is that the http body now has the text 'Failed to load source for: <a href="http://localhost:7000/bla" rel="noreferrer">http://localhost:7000/bla</a>..' instead of the actual JSON data..</p>
  
  <p>Any ideas? I'm considering using the last approach and just sticking the JSON in the HTTP StatusMessage header field instead of in the body, but this doesn't seem quite as nice?</p>