Set default response type in WCF Web Api

I have a set of services hosted with WCF Web Api and am communicating with them in JSON from javascript. In most cases, I normally change the accept bit in the header to require a JSON response, but there are some cases where I cannot do this. This is due to the javascript (Ext JS) system used. For some things, it allows me to specify a URL rather than default settings such as headers.

However, this is not an Ext JS issue. Web Api seems to return XML by default, and I would like to know if this default value can be changed so that it can return JSON. Thanks in advance!

+5
source share
4 answers

A little experimentation seems to indicate that the order of the configured formats matters (which is pretty intuitive).

By default, when creating an instance, HttpConfigurationits collection Formatterscontains the following formats:

  • XmlMediaTypeFormatter
  • JsonValueMediaTypeFormatter
  • JsonMediaTypeFormatter
  • FormUrlEncodedMediaTypeFormatter

The reason XML is the default formatting is because it is the first formatting. To make JSON the default, you can reorder the collection this way:

  • JsonValueMediaTypeFormatter
  • JsonMediaTypeFormatter
  • XmlMediaTypeFormatter
  • FormUrlEncodedMediaTypeFormatter

Given an instance of configHttpConfiguration, here is one way to change the collection order:

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 this is supported or not, I don’t know, but it seems to work on WebApi 0.6.0.

+4

. , JSON . text/html. , JSON, . , , accept . 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"));
+3

, http://blog.alexonasp.net/post/2011/07/26/Look-Ma-I-can-handle-JSONP-(aka-Cross-Domain-JSON)-with-WCF-Web-API-and-jQuery!.aspx, URI, http://myserver/myresource/1/json http://myserver/myresource/1 accept application/json.

ContactManager_Advanced, -API WCF http://wcf.codeplex.com.

It is contained in the UriFormatExtensionMessageChannel.cs file.

Take a look at the global.asax.cs example file on how to run it.

+2
source

According to the web API code, WCF will always use XmlFormatter by default if it is in the collection of formatters used. If JsonFormatter is used instead, if present. There is also a DefaultFormatter property, but this is internal, so you cannot set this. Maybe a useful feature request to add?

+1
source

All Articles