Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default response type in WCF Web Api

I've a set of services hosted with WCF Web Api and I communicate with them in JSON from javascript. In most cases I'm okay modifying the accepts bit of the header to require a JSON response but there are some cases arising where I can't do this. This is due the the javascript framework that I'm using (Ext JS). For some things it only lets me specify a URL and not the proxy defaults such as headers.

This isn't an Ext JS question however. Web Api seems to default to returning XML, and I'd like to know whether it's possible to change this default so that it can return JSON instead. Thanks in advance!

like image 850
Daniel Revell Avatar asked Jul 21 '11 16:07

Daniel Revell


2 Answers

A bit of experimentation seems to indicate that the order of the configured formatters matter (which is quite intuitive).

By default, when you create an instance of HttpConfiguration, its Formatters collection contains these formatters:

  1. XmlMediaTypeFormatter
  2. JsonValueMediaTypeFormatter
  3. JsonMediaTypeFormatter
  4. FormUrlEncodedMediaTypeFormatter

The reason why XML is the default formatting is because it's the first formatter. To make JSON the default value, you can reorder the collection to look like this:

  1. JsonValueMediaTypeFormatter
  2. JsonMediaTypeFormatter
  3. XmlMediaTypeFormatter
  4. FormUrlEncodedMediaTypeFormatter

Given an instance config of HttpConfiguration, here's one way to reorder the collection:

var jsonIndex = Math.Max(
    config.Formatters.IndexOf(config.Formatters.JsonFormatter),
    config.Formatters.IndexOf(config.Formatters.JsonValueFormatter));
var xmlIndex = config.Formatters.IndexOf(
    config.Formatters.XmlFormatter);

config.Formatters.Insert(jsonIndex + 1, config.Formatters.XmlFormatter);
config.Formatters.RemoveAt(xmlIndex);

Whether or not this is supported I don't know, but it seems to work on WebApi 0.6.0.

like image 127
Mark Seemann Avatar answered Sep 21 '22 06:09

Mark Seemann


I actually found a simple way of dealing with this. First make sure that the default JSON formatter is first. And then set its type to text/html. This will insure that the browser gets JSON even if it does not set the header. Nice aspect of the below is that you never have to remember to set the accept header in client code. It just works and always default to JSON.

var jsonformatter = config.Formatters.Where(t => t.GetType() == typeof(JsonMediaTypeFormatter)).FirstOrDefault());
config.Formatters.Remove(jsonformatter );
config.Formatters.Insert(0, jsonformatter); 
config.Formatters[0].SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
like image 39
AlexGad Avatar answered Sep 20 '22 06:09

AlexGad