ASP.NET的Web API返回的XML,而不是JSON的 [英] ASP.NET web api returning XML instead of JSON

查看:643
本文介绍了ASP.NET的Web API返回的XML,而不是JSON的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了,默认情况下,创造了一个API时的Web API将返回JSON数据,但由于某些原因,它返回XML而不是JSON。

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

推荐答案

如果您修改您的 WebApiConfig 如下,你会在默认情况下得到JSON。

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

这篇关于ASP.NET的Web API返回的XML,而不是JSON的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆