Custom HttpErrorHandler and ObjectContent returns wrong response type

Topics: Web Api
Sep 16, 2011 at 11:09 PM
Say I have a custom error handler:
 public class MyErrorHandler : HttpErrorHandler
    {
        protected override bool OnTryProvideResponse(Exception exception, ref HttpResponseMessage message)
        {
            message = new HttpResponseMessage
                          {
                              StatusCode = HttpStatusCode.InternalServerError,
                              Content = new ObjectContent<Response>(new MyCustomClass("foo""bar"))
                          };
            return true;
        }
    }

For some reason, if I have the accept type set to application/json, that error handler is still returning XML (I am guessing XML is the default).  When I create the ObjectContent instance, it does take a formatters parameter, but I am not sure how to get the proper MediaTypeFormatter (in my case I am using a JSON.net formatter).  I am trying to avoid hard-coding my json formatter here.

Sep 16, 2011 at 11:18 PM

We have a limitation at the moment where responses generated in error handlers don’t go through the full content negotiation which is why you see the default formatter getting picked. We do want to fix this but at the moment passing in your json formatter is a work-around.

Henrik

From: thekaido [email removed]
Sent: Friday, September 16, 2011 3:10 PM
To: Henrik Frystyk Nielsen
Subject: Custom HttpErrorHandler and ObjectContent returns wrong response type [wcf:272891]

From: thekaido

Say I have a custom error handler:
 public class MyErrorHandler : HttpErrorHandler
    {
        protected override bool OnTryProvideResponse(Exception exception, ref HttpResponseMessage message)
        {
            message = new HttpResponseMessage
                          {
                              StatusCode = HttpStatusCode.InternalServerError,
                              Content = new ObjectContent<Response>(new MyCustomClass("foo", "bar"))
                          };
            return true;
        }
    }

For some reason, if I have the accept type set to application/json, that error handler is still returning XML (I am guessing XML is the default). When I create the ObjectContent instance, it does take a formatters parameter, but I am not sure how to get the proper MediaTypeFormatter (in my case I am using a JSON.net formatter). I am trying to avoid hard-coding my json formatter here.

Sep 16, 2011 at 11:21 PM

Passing in my custom formatter doesn't work.  However passing in my media type "application/json" works.  I trying to find a way to pull the media type from the OperationContext.