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 >> Commented Aug 16, 2013 at 7:45
  • Possible duplication: link Commented 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);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

what's the explanation here? the last two lines are removing the xml formatter?
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 :/
Exactly what I was lookin' for !!
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.