ASP.NET web api returning XML instead of JSON

51,773

Solution 1

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);
    }
}

Solution 2

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.

Share:
51,773
clifford.duke
Author by

clifford.duke

Updated on December 24, 2020

Comments

  • clifford.duke
    clifford.duke about 2 years

    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