一聚教程网:一个值得你收藏的教程网站

热门教程

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

时间:2022-06-25 08:48:15 编辑:袖梨 来源:一聚教程网

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

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

 代码如下复制代码

publicclassPowerFilter : AuthorizeAttribute

 {

   publicoverridevoidOnAuthorization(AuthorizationContext filterContext)

   {

     var cookie = HttpContext.Current.Request.Cookies["loginInfo"];

     if(null== cookie)

     {

       filterContext.Result =newRedirectResult("/admin/login/index");

     }

     else

     {

       cookie.Expires = DateTime.Now.AddMinutes(30);

       HttpContext.Current.Response.Cookies.Remove("loginInfo");

       HttpContext.Current.Response.Cookies.Add(cookie);

     }

   }

 }

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

 代码如下复制代码

publicclassPowerFilter : AuthorizeAttribute

  {

    publicoverridevoidOnAuthorization(AuthorizationContext filterContext)

    {

      var cookie = HttpContext.Current.Request.Cookies["loginInfo"];

      if(null== cookie)

      {

        filterContext.Result =newContentResult()

        {

          Content =string

          .Format("

","/admin/login/index")

        };

      }

      else

      {

        cookie.Expires = DateTime.Now.AddMinutes(30);

        HttpContext.Current.Response.Cookies.Remove("loginInfo");

        HttpContext.Current.Response.Cookies.Add(cookie);

      }

    }

  }

}

但是,假如是ajax请求呢?

 代码如下复制代码

publicclassPowerFilter : AuthorizeAttribute

  {

    publicoverridevoidOnAuthorization(AuthorizationContext filterContext)

    {

      var cookie = HttpContext.Current.Request.Cookies["loginInfo"];

      if(null== cookie)

      {

        if(!filterContext.HttpContext.Request.IsAjaxRequest())

        {

          filterContext.Result =newContentResult()

          {

            Content =string

                 .Format("

","/admin/login/index")

          };

        }

        else

        {

          filterContext.Result =newJsonResult()

          {

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

      }

    }

  }

热门栏目