2

I have a WCF REST service whose interface methods are annotated with [WebGet(..., ResponseFormat = WebMessageFormat.Json)] and normally provide JSON-formatted responses. Right now the code indicates errors with:

throw new WebFaultException<string>("helpful message",HttpStatusCode.BadRequest);

The problem is that the Content-Type on the response is still application/json even though the body is just plain text, not JSON encoded. I can make a helper to generate my fault exceptions that will set WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";, but if there's a quick fix in the WCF layer that would just set the content type for these types of exceptions that would be preferable. What's the cleanest way to do this?

jtb
  • 889
  • 11
  • 27

1 Answers1

0

You can inherit the WebFaultException and use it in your project.

public class MyWebFaultException<T>:WebFaultException<T>
{
    public MyWebFaultException(T message)
        : base(message, HttpStatusCode.BadRequest)
    {
        WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
    }
}
Charlie
  • 1,292
  • 8
  • 7
  • This is about equivalent to the helper method approach. I was hoping to find a clean way to hook it into the WCF stack so that even if somebody missed the memo and threw the base WebFaultException class the content type would be correctly set. It looks like there's a way if I override the web behavior's `AddServerErrorHandlers`, but that got ugly fast. Making sure all the throws use the custom exception type or helper method would be better than what I came up with there. Still hoping there's a slicker answer though :-) – jtb Jul 31 '12 at 04:49