28

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

2
  • Nevermind, I found out it was actually returning JSON, for some reason Chrome was formatting it into XML >> Aug 16, 2013 at 7:45
  • Possible duplication: link Aug 16, 2013 at 9:26

2 Answers 2

65

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);
    }
}
3
  • 1
    what's the explanation here? the last two lines are removing the xml formatter?
    – FistOfFury
    Mar 10, 2020 at 17:24
  • 1
    Lovely, if you want to remove XML support (even when explicitly requested) and want this on all responses, Seems impossible to find information on how to enforce it on only one endpoint :/
    – NiKiZe
    Oct 1, 2020 at 10:42
  • Exactly what I was lookin' for !! Apr 8, 2022 at 9:07
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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.