How do I get ASP.NET Web API to return JSON instea

2018-12-31 03:44发布

Using the newer ASP.NET Web API, in Chrome I am seeing XML - how can I change it to request JSON so I can view it in the browser? I do believe it is just part of the request headers, am I correct in that?

29条回答
裙下三千臣
2楼-- · 2018-12-31 04:46

WebApiConfig is the place where you can configure whether you want to output in json or xml. by default it is xml. in the register function we can use HttpConfiguration Formatters to format the output . System.Net.Http.Headers => MediaTypeHeaderValue("text/html") is require to get the output in the json format. enter image description here

查看更多
只若初见
3楼-- · 2018-12-31 04:47

MVC4 Quick Tip #3–Removing the XML Formatter from ASP.Net Web API

In Global.asax add the line:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

like so:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    BundleTable.Bundles.RegisterTemplateBundles();
    GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}
查看更多
后来的你喜欢了谁
4楼-- · 2018-12-31 04:49

In the WebApiConfig.cs, add to the end of the Register function:

// Remove the XML formatter
config.Formatters.Remove(config.Formatters.XmlFormatter);

Source.

查看更多
千与千寻千般痛.
5楼-- · 2018-12-31 04:49

as per latest version of ASP.net WebApi 2,

under WebApiConfig.cs , this will work

config.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
config.Formatters.Add(GlobalConfiguration.Configuration.Formatters.JsonFormatter);
查看更多
倾城一夜雪
6楼-- · 2018-12-31 04:50

In the Global.asax I am using the code below. My URI to get JSON is http://www.digantakumar.com/api/values?json=true

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new  QueryStringMapping("json", "true", "application/json"));
}
查看更多
登录 后发表回答