Friday 26 October 2012

When Session times out before FormsAuthentication is dropped

Just wanted to keep this safe, there are probably better ways of doing this, but I often find that the FormsAuthentication object holds on to your login, after the session has cleared.

This often happens when I am testing a site and making changes, the site will drop it's session but the FormsAuthentication stays populated and logged in causing an error to be thrown until you logout and back into to repopulate the necessary session objects.

So in the OnInit event I add a simple check:
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        var current = Path.GetFileNameWithoutExtension(Request.PhysicalPath);
        if (current.StartsWith("Registration", StringComparison.InvariantCultureIgnoreCase) && Session["Objectx"] == null)
        {
            Response.Redirect("SignIn.aspx");
        }
    }

The above only worries about pages with the word Registration in then page name.

For an entire site you need to be a bit different:
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        var current = Path.GetFileNameWithoutExtension(Request.PhysicalPath);
        if (!current.Equals("SignIn", StringComparison.InvariantCultureIgnoreCase) && Session["Objectx"] == null)
        {
            Response.Redirect("SignIn.aspx");
        }
    }


No comments:

Post a Comment