ASP.MVC 重写JsonResult+扩展方法 定义统一JSON数据

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace common
{
   public class CustomJsonResult: JsonResult
    {
        /// <summary>
        /// 字段对象
        /// </summary>
        public object data { get; set; }
        /// <summary>
        /// 对象
        /// </summary>
        /// <param name="data"></param>
        public CustomJsonResult(object data)
        {
            this.data = data;
        }
        /// <summary>
        /// 自定义消息输出
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context==null)
            {
                throw new ArgumentNullException("context");
            }
            var response = context.HttpContext.Response;
            response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            Data = this.data;
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(Data);
            response.Write(json);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace common
{
   public static class Extensions
    {
        /// <summary>
        /// 扩展返回统一JSON
        /// </summary>
        /// <param name="data"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static CustomJsonResult Result( this object data,string msg=null)
        {
            if (msg==null)
            {
                var datas = new { target = data, code = 200, msg ="成功"};
                CustomJsonResult customJsonResult = new CustomJsonResult(datas);
                return customJsonResult;
            }
            else
            {
                var datas = new { target = data, code = 500, msg=msg };
                CustomJsonResult customJsonResult = new CustomJsonResult(datas);
                return customJsonResult;
            }
        }
    }
}
  /// <summary>
        /// 登入接口
        /// </summary>
        /// <param name="strJson"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(string data)
        {
            return true.Result();
        }

返回如下JSON

 

posted @ 2018-11-03 02:17  NET木下  阅读(912)  评论(0编辑  收藏  举报