MVC 3 中如何处理会话超时

发布于 2024-11-17 15:49:37 字数 88 浏览 0 评论 0原文

我遇到了频繁的会话超时问题。

我想编写一个可以在每个控制器上使用的通用过滤器,过滤器应重定向用户登录,并在登录后返回到用户发送最后一个请求的位置。

I am having issues with frequent Session Time Out.

I want to write a common filter that I could use on each controller, filter should redirect the user to login and after log in back to from where user sent the last request.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

宣告ˉ结束 2024-11-24 15:49:37

你可以尝试这样的事情:

public class SessionExpireAttribute : ActionFilterAttribute {
    public override void OnActionExecuted(ActionExecutedContext filterContext) {
        base.OnActionExecuted(filterContext);
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        if (filterContext.HttpContext.Session != null) {
            if (filterContext.HttpContext.Session.IsNewSession) {
                var sessionCookie = filterContext.HttpContext.Request.Headers["Cookie"];
                if ((sessionCookie != null) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)) {
                    // redirect to login
                }
            }
        }
    }
}

You could try something like this:

public class SessionExpireAttribute : ActionFilterAttribute {
    public override void OnActionExecuted(ActionExecutedContext filterContext) {
        base.OnActionExecuted(filterContext);
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        if (filterContext.HttpContext.Session != null) {
            if (filterContext.HttpContext.Session.IsNewSession) {
                var sessionCookie = filterContext.HttpContext.Request.Headers["Cookie"];
                if ((sessionCookie != null) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)) {
                    // redirect to login
                }
            }
        }
    }
}
小霸王臭丫头 2024-11-24 15:49:37

这里的东西比我们看到的还要多。这是一个更完整的 OnActionExecuting,它使用上面已经讨论过的相同概念,但添加了更多内容。有关更多信息,请参阅内嵌注释。被调用的“InitializeSession”是一个自定义函数,它创建会话状态中运行站点所需的基本属性。 “AlertWarning”是用于显示警报的帮助程序。其他一切都是样板代码。

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
  var bRequiresAuthorization =
    (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), false).Length > 0) ||
    (filterContext.Controller.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), false).Length > 0);

  if (filterContext.HttpContext.Session != null)
  {
    if (filterContext.HttpContext.Session.IsNewSession)
    {
      //New session.  Initialize Session State
      bool b = InitializeSession(null);

      if (bRequiresAuthorization )
      {
        //Action requested requires authorized access.   User needs to authenticate this
        //new session first, so redirect to login
        string cookie = filterContext.HttpContext.Request.Headers["Cookie"];
        if ( (cookie != null) && (cookie.IndexOf("_SessionId=") >= 0) )
        {
          //An expired session cookie still resides on this PC, so first alert user that session is expired
          AlertWarning("Session timed out due to inactivity.  Please log in again.");
        }
        filterContext.Result = RedirectToAction("LogOut", "Authentication");
      }
    }
  }

  base.OnActionExecuting(filterContext);

}

There's more here than meets the eye. Here's a more complete OnActionExecuting that uses the same concept already discussed above but adds a bit more. See inline comments for more info. The "InitializeSession" being called is a custom function which creates the basic attributes needed in Session State for running the site. "AlertWarning" is a Helper routine for displaying alerts. Everything else is boilerplate code.

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
  var bRequiresAuthorization =
    (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), false).Length > 0) ||
    (filterContext.Controller.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), false).Length > 0);

  if (filterContext.HttpContext.Session != null)
  {
    if (filterContext.HttpContext.Session.IsNewSession)
    {
      //New session.  Initialize Session State
      bool b = InitializeSession(null);

      if (bRequiresAuthorization )
      {
        //Action requested requires authorized access.   User needs to authenticate this
        //new session first, so redirect to login
        string cookie = filterContext.HttpContext.Request.Headers["Cookie"];
        if ( (cookie != null) && (cookie.IndexOf("_SessionId=") >= 0) )
        {
          //An expired session cookie still resides on this PC, so first alert user that session is expired
          AlertWarning("Session timed out due to inactivity.  Please log in again.");
        }
        filterContext.Result = RedirectToAction("LogOut", "Authentication");
      }
    }
  }

  base.OnActionExecuting(filterContext);

}
风启觞 2024-11-24 15:49:37

您是否尝试过现有的授权过滤器?

Have you tried the existing Authorize filter?

夏の忆 2024-11-24 15:49:37

如上所述..尝试这个

public class SessionExpireAttribute : ActionFilterAttribute {

    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        if (filterContext.HttpContext.Session != null) {
            if (filterContext.HttpContext.Session.IsNewSession) {
                filterContext.Result = new RedirectResult("/");//redirect to home page
            }
        }
    }
}

,然后在操作或控制器上应用这个过滤器[SessionExpire]

as mentioned above .. try this

public class SessionExpireAttribute : ActionFilterAttribute {

    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        if (filterContext.HttpContext.Session != null) {
            if (filterContext.HttpContext.Session.IsNewSession) {
                filterContext.Result = new RedirectResult("/");//redirect to home page
            }
        }
    }
}

and then apply this filter over the action or controller [SessionExpire]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文