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>
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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();
}
}
Method 2
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.
Method 3
I think you need to use Refresh instead of `Redirect’ in your header:
Response.AppendHeader("Refresh",
Convert.ToString((Session.Timeout * 60) - 3) +
";URL=~/Login.aspx");
Method 4
Here is an example I have that works for me:
<authentication mode="Forms">
<forms loginUrl="~/Login/Index" defaultUrl="~/Admin" timeout="20">
</forms>
</authentication>
If you have this, there is no need for you to check the timeout cookie yourself. This is assuming you are using Forms Authentication.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0