4

I want to have my web API to return JSON by default.

However, I still need to be able to support XML formatting.

When I do the following, it returns JSON:

public static void Register(HttpConfiguration config)
{
    config.Formatters.Clear();
    config.Formatters.Add(new JsonMediaTypeFormatter());
}

When I do the following, it returns XML (JSON if I had the json=true parameter)

public static void Register(HttpConfiguration config)
{
    config.Formatters.Clear();
    config.Formatters.Add(new XmlMediaTypeFormatter());
    config.Formatters.Add(new JsonMediaTypeFormatter());
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("json", "true", "application/json"));

}

When I do this, it returns XML all the time. Parameter or not..

I would like JSON with no parameter, XML when parameter is specified.

public static void Register(HttpConfiguration config)
{
    config.Formatters.Clear();
    config.Formatters.Add(new JsonMediaTypeFormatter());
    config.Formatters.Add(new XmlMediaTypeFormatter());
    GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("xml", "true", "application/xml"));
}
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
Baral
  • 3,103
  • 2
  • 19
  • 28
  • 1
    What are you using to make the request? Can you post an example HTTP request? – dav_i Oct 15 '14 at 16:49
  • 1
    possible duplicate of [How do I get ASP.NET Web API to return JSON instead of XML using Chrome?](http://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome) – Matt Johnson-Pint Oct 15 '14 at 17:46

1 Answers1

3

I think the default when all else is equal is the first on in the list.

Have you tried:

public static void Register(HttpConfiguration config)
{
    config.Formatters.Clear();
    config.Formatters.Add(new JsonMediaTypeFormatter());
    config.Formatters.Add(new XmlMediaTypeFormatter());   
}

Alternately, you can specifically define a content negotiation strategy. Details about how it works in Web API are here: http://www.asp.net/web-api/overview/formats-and-model-binding/content-negotiation

A sample implementation is here: http://www.strathweb.com/2013/06/supporting-only-json-in-asp-net-web-api-the-right-way/

xero
  • 177
  • 2
  • 9