29

I read that by default, Web API will return JSON Data but for some reason when creating an API, it returns XML instead of JSON.

public class CurrencyController : ApiController
{
    private CompanyDatabaseContext db = new CompanyDatabaseContext();

    // GET api/Currency
    public IEnumerable<Currency> GetCurrencies()
    {
        return db.Currencies.AsEnumerable();
    }
}

I haven't modified anything out of the ordinary so I'm stumped

clifford.duke
  • 3,980
  • 10
  • 38
  • 63
  • Nevermind, I found out it was actually returning JSON, for some reason Chrome was formatting it into XML >> – clifford.duke Aug 16 '13 at 07:45
  • Possible duplication: [link](http://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome) – Fernando Vezzali Aug 16 '13 at 09:26

2 Answers2

64

if you modify your WebApiConfig as follows you'll get JSON by default.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
    }
}
chamara
  • 12,649
  • 32
  • 134
  • 210
18

Web Api looks for the headers of the upcoming request to choose the returning data type. For instance, if you set Accept:application/json it will automatically set the returning type to JSON.

Besides that, setting content-type gives a clue to Web-API about upcoming request data type. So if you want to post JSON data to Web API you should have Content-Type:application/json in header.

kkocabiyik
  • 4,246
  • 7
  • 30
  • 40