ASP.NET web api returning XML instead of JSON

This question already has an answer here:

  • How do I get ASP.NET Web API to return JSON instead of XML using Chrome? 29 answers

  • 如果您按照以下方式修改WebApiConfig ,则默认情况下会获得JSON。

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

    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.

    链接地址: http://www.djcxy.com/p/20414.html

    上一篇: Web API应该默认返回JSon

    下一篇: ASP.NET web api返回XML而不是JSON