views:

94

answers:

0

My ASP.NET 3.5sp1 MVC app uses the following filter attribute class to implement session timeout behavior. It does work to an extent in that it takes user to the login page and forces login however when the filter is executed again it always detects a timeout and returns user to the login page. The only way to proced is to clear the browser history(cookies) and then everything works fine. I feel that my login action should clear the session cookie so that the app does not still detect a timeout situation. I am unsure of how to do this or if another solution would be better. Here is my filter attribute code followed by my login action. Thanks.

 public class SessionExpireFilterAttribute : ActionFilterAttribute
{

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext ctx = HttpContext.Current;

        // check if session is supported
        if (ctx.Session != null)
        {

            // check if a new session id was generated
            if (ctx.Session.IsNewSession)
            {

                // If it says it is a new session, but an existing cookie exists, then it must
                // have timed out
                string sessionCookie = ctx.Request.Headers["Cookie"];
                if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
                {
                    ctx.Response.Redirect("~/Account/Login");
                }
            }
        }

        base.OnActionExecuting(filterContext);
    }
}

login action:

    public ActionResult Login(string username, string password, bool? rememberMe)
    {

        ViewData["Title"] = "Login";

        // Basic parameter validation

        List<string> errors = new List<string>();

        // Non-POST requests should just display the Login form 
        if (Request.HttpMethod != "POST")
        {
            return View();
        }

        if (String.IsNullOrEmpty(username))
        {
            errors.Add("You must specify a username.");
        }

        if (errors.Count == 0)
        {

            // Attempt to login
            bool loginSuccessful = Provider.ValidateUser(username, password);

            if (loginSuccessful)
            {

                FormsAuth.SetAuthCookie(username, rememberMe ?? false);
                return RedirectToAction("Welcome", "Home");
            }
            else
            {
                errors.Add("The username or password provided is incorrect.");
            }
        }

        // If we got this far, something failed, redisplay form
        ViewData["errors"] = errors;
        ViewData["username"] = username;
        return View();
    }