51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

【ASP.NET MVC】重写JsonResult

本文最后更新于 2024-05-07,文章可能存在过时内容,如有过时内容欢迎留言或者联系我进行反馈。

  1. 新建一个类 CustomesJsonResult 继承自 MVC 自带的 JsonResult,重写它的 ExecuteResult 方法

    public class JsonConvertResult : JsonResult
    {
        public JsonConvertResult()
        {
            Settings = new JsonSerializerSettings
            {
                //这句是解决Json序列化循环引用问题的关键,也就是json.net官方给出的解决配置选项
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };
        }
    
        /// <summary> 指定Json对象序列化设置 </summary>
        public JsonSerializerSettings Settings { get; private set; }
    
        /// <summary> 重写执行视图 </summary>
        /// <param name="context"> 上下文 </param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context <span style="font-weight: bold;" class="mark"> null)
                throw new ArgumentNullException("context");
            if (this.JsonRequestBehavior </span> JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
                throw new InvalidOperationException("JSON GET is not allowed");
    
            var response = context.HttpContext.Response;
            response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
            if (ContentEncoding != null)
                response.ContentEncoding = ContentEncoding;
    
            var jsonSerizlizerSetting = new JsonSerializerSettings();
            //设置取消循环引用
            jsonSerizlizerSetting.MissingMemberHandling = MissingMemberHandling.Ignore;
            //设置首字母小写
            jsonSerizlizerSetting.ContractResolver = new CamelCasePropertyNamesContractResolver();
            //设置日期的格式为:yyyy-MM-dd HH:mm
            jsonSerizlizerSetting.DateFormatString = "yyyy-MM-dd HH:mm";
            var json = JsonConvert.SerializeObject(Data, Formatting.None, jsonSerizlizerSetting);
            response.Write(json);
        }
    
    
    
    `}`
    
  2. 新建一个 BaseController 并继承自 Controller

    public class BaseController : Controller
    {
        /// <summary> 重写将对象序列化为 JavaScript 对象 </summary>
        /// <param name="data"> 要序列化的 JavaScript 对象 </param>
        /// <param name="contentType"> 内容类型(MIME 类型) </param>
        /// <param name="contentEncoding"> 内容编码 </param>
        /// <param name="behavior"> JSON 请求行为 </param>
        /// <returns> </returns>
        protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            return new JsonConvertResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior };
        }
    }
    

赞(0)
未经允许不得转载:工具盒子 » 【ASP.NET MVC】重写JsonResult