asp.net-mvc ASP.NET web api 返回 XML 而不是 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18266952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET web api returning XML instead of JSON
提问by clifford.duke
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.
我读到默认情况下,Web API 将返回 JSON 数据,但由于某种原因,在创建 API 时,它返回 XML 而不是 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
我没有修改任何异常的东西所以我很难过
回答by chamara
if you modify your WebApiConfigas follows you'll get JSON by default.
如果您按如下方式修改您的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);
}
}
回答by kkocabiyik
Web Api looks for the headers of the upcoming request to choose the returning data type. For instance, if you set Accept:application/jsonit will automatically set the returning type to JSON.
Web Api 查找即将到来的请求的标头以选择返回的数据类型。例如,如果您设置Accept:application/json,它将自动将返回类型设置为 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/jsonin header.
除此之外,设置 content-type 为 Web-API 提供了有关即将到来的请求数据类型的线索。因此,如果您想将 JSON 数据发布到 Web API,您应该在标题中包含Content-Type:application/json。

