代码改变世界

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

2018-12-19 18:21  音乐让我说  阅读(1406)  评论(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
    }
}

 

谢谢浏览!