1. 程式人生 > >ASP.MVC 重寫JsonResult+擴充套件方法 定義統一JSON資料

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