欢迎来到资源库(www.zyku.net)

ASP.NET

当前位置:首页 > 网络编程 > ASP.NET > .NET

Asp.net 中mvc 实现超时弹窗后跳转功能

时间:2017-02-17|栏目:ASP.NET|点击:|我要投稿

为了实现保持登录状态,可以用cookie来解决这一问题

假设过期时间为30分钟,校验发生在服务器,借助过滤器,可以这样写

public class PowerFilter : AuthorizeAttribute
 {
   public override void OnAuthorization(AuthorizationContext filterContext)
   {
     var cookie = HttpContext.Current.Request.Cookies["loginInfo"];
     if(null == cookie)
     {
       filterContext.Result = new RedirectResult("/admin/login/index");
     }
     else
     {
       cookie.Expires = DateTime.Now.AddMinutes(30);
       HttpContext.Current.Response.Cookies.Remove("loginInfo");
       HttpContext.Current.Response.Cookies.Add(cookie);
     }
   }
 }

但是页面直接跳转了,也没有一个提示,显得不是很友好,可以这样

public class PowerFilter : AuthorizeAttribute
  {
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
      var cookie = HttpContext.Current.Request.Cookies["loginInfo"];
      if(null == cookie)
      {
        filterContext.Result = new ContentResult()
        {
          Content = string
          .Format("<script>alert('登录超时,请重新登录');location.href='{0}'</script>","/admin/login/index")
        };
      }
      else
      {
        cookie.Expires = DateTime.Now.AddMinutes(30);
        HttpContext.Current.Response.Cookies.Remove("loginInfo");
        HttpContext.Current.Response.Cookies.Add(cookie);
      }
    }
  }
}

但是,假如是ajax请求呢?

public class PowerFilter : AuthorizeAttribute
  {
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
      var cookie = HttpContext.Current.Request.Cookies["loginInfo"];
      if(null == cookie)
      {
        if(!filterContext.HttpContext.Request.IsAjaxRequest())
        {
          filterContext.Result = new ContentResult()
          {
            Content = string
                 .Format("<script>alert('登录超时,请重新登录');location.href='{0}'</script>","/admin/login/index")
          };
        }
        else
        {
          filterContext.Result = new JsonResult()
          {
            Data = new { logoff = true,logurl = "/admin/login/index" },
            ContentType = null,
            ContentEncoding = null,
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
          };
        }
      }
      else
      {
        cookie.Expires = DateTime.Now.AddMinutes(30);
        HttpContext.Current.Response.Cookies.Remove("loginInfo");
        HttpContext.Current.Response.Cookies.Add(cookie);
      }
    }
  }

原文链接:http://www.cnblogs.com/cheesebar/archive/2017/02/10/6386479.html

(资源库 www.zyku.net)

上一篇:ASP.NET Core中使用默认MVC路由的配置

栏    目:ASP.NET

下一篇:ASP.NET MVC页面重定向简单介绍

本文标题:Asp.net 中mvc 实现超时弹窗后跳转功能

本文地址:https://www.zyku.net/aspnet/527.html

关于我们 | 版权申明 | 寻求合作 |

重要申明:本站所有的文章、图片、评论等内容,均由网友发表或上传并维护或收集自网络,仅供个人学习交流使用,版权归原作者所有。

如有侵犯您的版权,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:95148658 | 邮箱:mb8#qq.com(#换成@)

苏ICP备2020066115号-1

本网站由提供CDN加速/云存储服务