Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto redirect to login after session timeout

I am trying to redirect automatically to my login page after session times out. I tried to add this code in my Main.Master page (all the other pages are connected to this master page):

protected void Page_Load(object sender, EventArgs e)
{
            //Redirects to Login Page 3 seconds before session timeout
            Response.AppendHeader("Redirect", Convert.ToString((Session.Timeout * 60) - 3) + "; URL=~/Login.aspx");
}

I configured the session timeout to 1 minute in my web config:

<sessionState mode="InProc" cookieless="false" timeout="1"/>

but nothing happens

Can anyone help me find the problem with this code, or has other ideas how to make it work?

Edit: Authentication node from web.config

<authentication mode="Forms">
    <forms name=".CAuthenticated" loginUrl="Login.aspx" protection="All" 
    timeout="20"/>
</authentication>
like image 846
Inbal Avatar asked Mar 26 '26 23:03

Inbal


2 Answers

protected void Page_Init(object sender, EventArgs e)
{
    if (Session["Username"] == null)
    {
        Response.Redirect(ResolveClientUrl("~/login.aspx") + "?returnURL=" + HttpContext.Current.Request.Url.AbsolutePath);
    }
    else
    {
        lblUsername.Text = Session["Username"].ToString();
    }
}

AppendHeader is documented as causing an exception if "header is appended after the HTTP headers have been sent" You need to make sure AppendHeader is called before the HTTP headers have been sent. Depending on your master page, the Load event might be too late. You could try the Init event instead.

like image 27
Peter Ritchie Avatar answered Mar 29 '26 14:03

Peter Ritchie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!