Custom application/json media type formatter

Topics: Web Api
Apr 20, 2011 at 4:21 AM

Hello

How can I use custom 'application/json' media type formatter?

Coordinator
Apr 20, 2011 at 4:33 AM
Like using Json.net?

First create a custom JsonNetMediaTypeFormatter derived from MediaTypeFormatter.

In the ctor add the media type to SupportedMediaTypes.

Create a custom HttpOperationHandlerFactory. In the ctor add your factory add your new formatter to the beginning of the list of formatters .

Register your factory on the config class using SetOperationHandlerFactory

Adding third party formatters is easy, but replacing the existing one takes a few more steps.

I think we can work on simplifying that in the fi so that you can clear in AddFormatters without needing a custom factory


Sent from my Windows Phone

From: A1exander
Sent: Tuesday, April 19, 2011 8:21 PM
To: Glenn Block
Subject: Custom application/json media type formatter [wcf:254594]

From: A1exander

Hello

How can I use custom 'application/json' media type formatter?

Apr 20, 2011 at 6:44 AM

It does exactly what I need. Thanks!

Apr 22, 2011 at 7:13 PM

Is it still the case that we must create our own factory or can we simply:

            var builder = HttpHostConfiguration.Build()
                .AddFormatters(new DynamicRequestFormatter()));


I'm guessing so since my formatter never gets called. If so what's the purpose of AddFormatter()?

Cheers
Coordinator
Apr 22, 2011 at 7:36 PM
You can use that method if you are just adding. If you are replacing like our json stuff that won't work.

Sent from my Windows Phone

From: robstove
Sent: Friday, April 22, 2011 11:14 AM
To: Glenn Block
Subject: Re: Custom application/json media type formatter [wcf:254594]

From: robstove

Is it still the case that we must create our own factory or can we simply:

            var builder = HttpHostConfiguration.Build()
                .AddFormatters(new DynamicRequestFormatter()));


I'm guessing so since my formatter never gets called. If so what's the purpose of AddFormatter()?

Cheers
Jul 5, 2011 at 7:20 PM

If the static method DelegateOperationHandlerFactory.GetFormatters is changed to:

private static MediaTypeFormatterCollection GetFormatters(IEnumerable<MediaTypeFormatter> formatters)
        {
            var mediaTypeFormatters = new MediaTypeFormatterCollection();
            foreach(var formatter in formatters.Reverse())
                mediaTypeFormatters.Insert(0, formatter);
            return mediaTypeFormatters;
        }

Won't this make the user formatters take precedence over the defaults ?