小菜学习MVC4-WebApi

今天想看下MVC4的东西,发现 居然有WebApi这东西,百度了一下..居然是 WCF中的东西,然后移植到了MVC4中,WCF你懂得返回数据都是xml,向网站这种请求 就比较纠结...而webapi可以返回xml 和json等多种类型..效果比较好 你懂得...

科普文连接:WCF和ASP.NET Web API在应用上的选择 

WCF WebAPI 新动向,并入ASP.net MVC4

等等.......

开始正文...新建MVC4项目 选择WebApi 然后 等待...

运行测试...请求网址 为 http://localhost:55763/api/values (端口号自己修....)

咦,等等,返回格式居然是xml ,说好的json呢......

继续搜资料...找到了....   webapi返回数据同时支持xml与json

解决方法: 在自己的WebApiConfig文件,在 Register 方法中添加以下代码

 GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("json", "true", "application/json"));

或者:

config.Formatters.JsonFormatter.AddQueryStringMapping("json", "true", "application/json");

当需要返回json的数据时,就在访问的url后面加上 json=true,需要xml就写json=false

继续请求: http://localhost:55763/api/values?json=true

ok 成功返回 json格式

原文地址:https://www.cnblogs.com/rufus-hua/p/3350276.html