zoukankan      html  css  js  c++  java
  • asp.net webapi 返回json结果的方法

    第一种:

            public static void Register(HttpConfiguration config) {
    
                //1、将默认的xml格式化程序清除
                GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
    
                //2、设置默认返回json格式的数据
                GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("dataType","json","application/json"));            
    
                //3、如果设置http://xxx?dataType=xml,则返回xml格式的数据
                GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("dataType", "xml", "application/xml"));
    
                // Web API 配置和服务
    
                // Web API 路由
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
    
                config.Routes.MapHttpRoute(
                   name: "DefaultApi2",
                   routeTemplate: "api/{controller}/{action}/{id}",
                   defaults: new { id = RouteParameter.Optional }
               );
            }
        }

    Action的使用方式:

            [AcceptVerbs("GET", "POST")]        
            [Route("FetchList")]
            public Resultx FetchList() {
                return new Resultx { Code = 0, Message = "OK", Result = new { name="list",list=new List<string> { "1","2"} } };
            }

    第二种:

            [AcceptVerbs("GET", "POST")]
            [Route("FetchList")]
            //使用IHttpActionResult接口,用JsonResult<>()来返回Json字符串
            public IHttpActionResult FetchList() {
                return Json(new { Code = 0, Message = "OK", Result = new { name = "list", list = new List<string> { "1", "2" } } });
            }

    以上两种结果都能正常返回Json字符串:

    {"Code":0,"Message":"OK","Result":{"name":"list","list":["1","2"]}}
    

      

  • 相关阅读:
    Linux性能调优
    Linux动态库搜索路径的技巧
    [转]Linux动态库的种种要点
    [转]谈谈Linux下动态库查找路径的问题
    性能测试的几种业务模型设计
    性能测试解惑之并发压力
    一个系统的最大并发用户数为1100,怎么能推算出该系统的支持最大用户数
    IP欺骗
    关于Cocos2d-x随机数的生成
    关于Cocos2d-x节点和精灵节点的坐标、位置以及大小的设置
  • 原文地址:https://www.cnblogs.com/williamwsj/p/7413013.html
Copyright © 2011-2022 走看看