Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC 3: Where to handle session loss?

I've started bumping into errors when my session has been lost, or upon rebuilding my project, as my forms authentication cookie still lives on.

In WebForms I'd use the masterpage associated with pages which require login to simply check for the session.

How would I do this in one location in MVC ? I'd hate having to check for session state in every action in my controllers.

On the other hand I can't just apply a global filter either, since not all Controllers require session state.

Would it perhaps be possible in my layout view ? It's the only thing the pages which require session have in common.

like image 620
Steffen Avatar asked Oct 12 '22 13:10

Steffen


2 Answers

One thing you could do is to sub-class the controllers that do need session state. This way you could create a filter on just this base controller. This would allow you to do it all in one place. Plus, as you pointed out, a global filter won't help you here since the logic does not apply to every controller.

like image 194
Steve Michelotti Avatar answered Oct 20 '22 14:10

Steve Michelotti


add it to session start. if a session loss happens it needs to trigger a session start too. you can handle it in there as follows:

protected void Session_Start(object src, EventArgs e)
    {
        if (Context.Session != null)
        {
            if (Context.Session.IsNewSession)
            {
                string sCookieHeader = Request.Headers["Cookie"];
                if ((null != sCookieHeader) && (sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
                {
                    // how to simulate it ???   
                    // RedirectToAction(“ActionName”, “ControllerName”,  route values);  
                    Response.Redirect("/Home/TestAction");
                }

            }
        }


    }
like image 38
Baz1nga Avatar answered Oct 20 '22 14:10

Baz1nga