ASP.NET MVC 自定义处理JSON ActionResult类


1、统一JSON格式处理方式,同时指定ContentType类型,解决低版本浏览器获取json时ContentType为application/json提示下载的问题.

 public abstract class CustomResult<TData> : ActionResult
    {
        public abstract TData GetObject();

        protected JsonSerializerSettings SerializerSettings;

        protected void InitSerialization(ControllerContext context)
        {
            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = "text/html";
            TData data = GetObject();
            if (SerializerSettings == null)
            {
                SetSerializerSettings();
            }
            response.Write(JsonConvert.SerializeObject(data, Formatting.None, SerializerSettings));
        }

        protected virtual void SetSerializerSettings()
        {
            SerializerSettings = new JsonSerializerSettings
            {              
                Converters = new List<JsonConverter>
                {
                    new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd hh:mm" }
                }
            };
        }

        public override void ExecuteResult(ControllerContext context)
        {
            InitSerialization(context);
        }
    }

 

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM