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

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

问题描述

我读到默认情况下,Web API 将返回 JSON 数据,但由于某种原因,在创建 API 时,它返回 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天全站免登陆