开发者

How to handle Session timeout in MVC 3

开发者 https://www.devze.com 2023-03-16 22:33 出处:网络
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 use开发者_JS百科r to login and after log in back to

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 use开发者_JS百科r to login and after log in back to from where user sent the last request.


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


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

}


Have you tried the existing Authorize filter?


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]

0

精彩评论

暂无评论...
验证码 换一张
取 消