首页 > Web开发 > 详细

ASP.NET MVC 下自定义 JsonResult,使用 Json.NET 序列化 JSON

时间:2018-12-19 18:56:57      阅读:126      评论:0      收藏:0      [点我收藏+]

直接贴代码了:

using System;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace MvcSample.Extensions
{
    public class ConverterJsonResult : JsonResult
    {
        #region Fields

        private readonly JsonConverter[] _converters;

        #endregion

        #region Ctor

        public ConverterJsonResult(params JsonConverter[] converters)
        {
            _converters = converters;
        }

        #endregion

        #region Methods

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            if (context.HttpContext == null || context.HttpContext.Response == null)
                return;

            context.HttpContext.Response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
            if (ContentEncoding != null)
                context.HttpContext.Response.ContentEncoding = ContentEncoding;

            if (Data != null)
                context.HttpContext.Response.Write(JsonConvert.SerializeObject(Data, _converters));
        }

        #endregion
    }
}

 

谢谢浏览!

ASP.NET MVC 下自定义 JsonResult,使用 Json.NET 序列化 JSON

原文:https://www.cnblogs.com/Music/p/custom-json-result-in-asp-net-mvc.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!