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);
        }
    }

 

  

你可能感兴趣的:(asp.net)