• MVC AOP解决JsonResult返回json时间格式


    新建JsonNetResult类:JsonResult

    public class JsonNetResult: JsonResult
        {
            public JsonNetResult()
            {
                Settings = new JsonSerializerSettings
                {
                    ReferenceLoopHandling=ReferenceLoopHandling.Ignore,
                    DateFormatString= "yyyy-MM-dd HH:mm:ss",
                    ContractResolver=new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()//json中属性开头字母小写的驼峰命名
                };
            }
            public JsonSerializerSettings Settings { get; private set; }
    
            public override void ExecuteResult(ControllerContext context)
            {
                if (context == null)
                    throw new ArgumentNullException("context");
                //不允许GET请求
                if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet
                    && string.Equals(context.HttpContext.Request.HttpMethod, "GET",
                    StringComparison.OrdinalIgnoreCase))
                    throw new InvalidOperationException("JSON GET is not allowed");
    
                HttpResponseBase response = context.HttpContext.Response;
                response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
    
                if (this.ContentEncoding != null)
                    response.ContentEncoding = this.ContentEncoding;
                if (this.Data == null)
                    return;
                var scriptSerializer = JsonSerializer.Create(this.Settings);
                scriptSerializer.Serialize(response.Output, this.Data);
            }
        }
    

      新建JsonNetActionFilter过滤器:

    public class JsonNetActionFilter: IActionFilter
        {
            public void OnActionExecuted(ActionExecutedContext filterContext)
            {
                if (filterContext.Result is JsonResult
                    && !(filterContext.Result is JsonNetResult))
                {
                    JsonResult jsonResult = (JsonResult)filterContext.Result;
                    JsonNetResult jsonNetResult = new JsonNetResult();
    
                    jsonNetResult.ContentEncoding = jsonResult.ContentEncoding;
                    jsonNetResult.ContentType = jsonResult.ContentType;
                    jsonNetResult.Data = jsonResult.Data;
                    jsonNetResult.JsonRequestBehavior = jsonResult.JsonRequestBehavior;
                    jsonNetResult.MaxJsonLength = jsonResult.MaxJsonLength;
                    jsonNetResult.RecursionLimit = jsonResult.RecursionLimit;
    
                    filterContext.Result = jsonNetResult;
                }
            }
    
            public void OnActionExecuting(ActionExecutingContext filterContext)
            {
    
            }
        }
    

      在Global中添加

     GlobalFilters.Filters.Add(new JsonNetActionFilter());
    

      控制器:

         [HttpGet]
            public ActionResult TestJson()
            {
                return View();
            }
            [HttpPost]
            public ActionResult TestJson(FormCollection fc)
            {
                Dog dog = new Dog()
                {
                    BirthDay = DateTime.Now,
                    Id = 5,
                    Name = "旺财"
                };
                return Json(dog);
                //return new JsonNetResult() { Data = dog };
            }
    

      前端:

        <script type="text/javascript">
            $(function () {
                $("#btn1").click(function () {
                    $.ajax({
                        url: "/Home/TestJson",
                        dataType: "json",
                        type: "post",
                        success: function (data) {
                            alert(data.name);
                            alert(data.birthDay);
                        },
                        error: function () {
                            alert("ajax错误");
                        }
                    });
                });
            });
        </script>
    

      

  • 相关阅读:
    依赖反转Ioc和unity,autofac,castle框架教程及比较
    webform非表单提交时防xss攻击
    tfs分支操作
    防火墙入站出站规则配置
    前端流程图jsplumb学习笔记
    Js闭包学习笔记
    word中加入endnote
    Rest概念学习
    DRF的版本、认证、权限
    博客园自动生成目录
  • 原文地址:https://www.cnblogs.com/sunliyuan/p/10370296.html
Copyright © 2020-2023  润新知