1、Global 中增加json输出

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("json", "true", "application/json"));
 protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
//添加json 解析 使用方法 http://xxx/api/action?json=true
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("json", "true", "application/json"));
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}

2、Global 中删除xml解析

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
 protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//删除xml的解析 当返回值是string 时 直接返回string不是json对象
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}

3、指定返回格式

 新建方法 需要程序集:System.Web.Extensions
public static HttpResponseMessage ToJson(Object obj)
{
String str;
if (obj is String || obj is Char)
{
str = obj.ToString();
}
else
{
var serializer = new JavaScriptSerializer();
str = serializer.Serialize(obj);
}
var result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}

调用户方法转换为json对象输出

 public HttpResponseMessage GetString(string name)
{
return ToJson(name);
}

4、重写默认实现类 所有输出将被重新解析成 json

 新建JsonContentNegotiator 类
public class JsonContentNegotiator : IContentNegotiator
{
private readonly JsonMediaTypeFormatter _jsonFormatter;
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
{
_jsonFormatter = formatter;
} public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
return result;
}
}
 WebApiConfig中使用重写
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
); var jsonFormatter = new JsonMediaTypeFormatter();
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter)); // 取消注释下面的代码行可对具有 IQueryable 或 IQueryable<T> 返回类型的操作启用查询支持。
// 若要避免处理意外查询或恶意查询,请使用 QueryableAttribute 上的验证设置来验证传入查询。
// 有关详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=279712。
//config.EnableQuerySupport(); // 若要在应用程序中禁用跟踪,请注释掉或删除以下代码行
// 有关详细信息,请参阅: http://www.asp.net/web-api
config.EnableSystemDiagnosticsTracing();
}

.Net MVC 4 Web Api 输出Json 格式的更多相关文章

  1. Web API删除JSON格式的文件记录

    Insus.NET的系列Web Api学习文章,这篇算是计划中最后一篇了,删除JSON格式的文件记录.前一篇<Web Api其中的PUT功能演示>http://www.cnblogs.co ...

  2. 企业IM (或业务系统)web api的json格式设计思考(原创)

    在企业IM开发中,经常用到和业务系统的数据交换,在中国企业最常见的比如组织架构变更,一般在客户端加密保存了组织架构树(便于快速的查询和树展示),当HR或OA或AD域这些管控企业组织架构的数据发生改变, ...

  3. .net mvc web api 返回 json 内容,过滤值为null的属性

    原文:http://blog.csdn.net/xxj_jing/article/details/49508557 版权声明:本文为博主原创文章,未经博主允许不得转载. .net mvc web ap ...

  4. MVC web api 返回JSON的几种方式,Newtonsoft.Json序列化日期时间去T的几种方式。

    原文链接:https://www.muhanxue.com/essays/2015/01/8623699.html MVC web api 返回JSON的几种方式 1.在WebApiConfig的Re ...

  5. ASP.NET MVC和Web API中的Angular2 - 第2部分

    下载源码 内容 第1部分:Visual Studio 2017中的Angular2设置,基本CRUD应用程序,第三方模态弹出控件 第2部分:使用Angular2管道进行过滤/搜索,全局错误处理,调试客 ...

  6. 使用 ASP.NET Core MVC 创建 Web API——响应数据的内容协商(七)

    使用 ASP.NET Core MVC 创建 Web API 使用 ASP.NET Core MVC 创建 Web API(一) 使用 ASP.NET Core MVC 创建 Web API(二) 使 ...

  7. 使用 ASP.NET Core MVC 创建 Web API(四)

    使用 ASP.NET Core MVC 创建 Web API 使用 ASP.NET Core MVC 创建 Web API(一) 使用 ASP.NET Core MVC 创建 Web API(二) 使 ...

  8. [Asp.Net] MVC 和Web API Action 获取参数的区别

    Asp.net MVC 和web api 的action 在获取从前台传入的数据是有很大不同 前台使用ajax的方式向后台发起post的请求 Content-Type:application/json ...

  9. Asp.Net MVC及Web API框架配置会碰到的几个问题及解决方案(转)

      前言 刚开始创建MVC与Web API的混合项目时,碰到好多问题,今天拿出来跟大家一起分享下.有朋友私信我问项目的分层及文件夹结构在我的第一篇博客中没说清楚,那么接下来我就准备从这些文件怎么分文件 ...

随机推荐

  1. jfinal的ajax例子

    @(编程) 简介 JFinal 是基于 Java 语言的极速 WEB + ORM 框架,其核心设计目标是开发迅速.代码量少.学习简单.功能强大.轻量级.易扩展.Restful. 在拥有Java语言所有 ...

  2. hdu 4738 Caocao's Bridges(桥的最小权值+去重)

    http://acm.hdu.edu.cn/showproblem.php?pid=4738 题目大意:曹操有一些岛屿被桥连接,每座都有士兵把守,周瑜想把这些岛屿分成两部分,但他只能炸毁一条桥,问最少 ...

  3. 移动端页面的head头部内容

  4. SpringMVC3.2+JPA使用注解的方式环境搭建

    ==============================entity=========================================================package ...

  5. easyui datagrid 的分页刷新按钮

    datagrid  刷新bug: 情形: 当用户A,B  同时操作 datagrid时(记录1,记录2.记录3).如果A如果删除记录1,  B此时已选中了记录1 ,记录2 , 这时B点击分页中的刷新按 ...

  6. 有关ListBox

    如何拿到Source:从SQL,从XML file SQL:一个是ObjectDataProvider //用linq方法拿到SQL data,wrap到一个IEnumerable<Custom ...

  7. HITAG 1/2/S

    HITAG S -- 3rd generation HITAG™ family Modulation Read/Write Device to Transponder: 100 % ASK and B ...

  8. IE6下z-index失效

    一.匆匆带过的概念关于CSS中层级z-index的定义啊什么的不是本文的重点,不会花费过多篇幅详细讲述.这里就简单带过,z-index伴随着层的概念产生的.网页 中,层的概念与photoshop或是f ...

  9. 【JavaScript】JS的启动机制

    DOM  Event------------------>触发function() function  自身的调用 主要就是调用function 1.DOM Event 2.调用function

  10. [Angular 2] Move and Delete Angular 2 Components After Creation

    After the original order is set, you can still leverage methods on the Angular 2 ViewContainer to re ...