问题
I try to set a rather long session time of 60 minutes on my web site by setting in web.config the authentication / forms / timeout value, and also by setting in code behind of the login page FormsAuthenticationTicket.expiration. However, already in 20 minutes, way too early, data in my Session variable got lost. How does this work and how do I fix it?
Web.config:
<authentication mode="Forms">
<forms name="MYWEBAPP.ASPXAUTH"
loginUrl="~/Login.aspx"
protection="All"
timeout="60" /* <<------ */
slidingExpiration="true"
path="/"/>
</authentication>
login.aspx.cs:
// Create a new ticket used for authentication
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Ticket version
LoggedInUser.LoginNm.ToString(), // Username associated with ticket
DateTime.Now, // Date/time issued
DateTime.Now.AddMinutes(60), // <<--- // Date/time to expire, minutes, use same value as in web.config or result is unclear
false, // "true" for a persistent user cookie
LoggedInUser.UserID.ToString(), // User-data, in this case user object
FormsAuthentication.FormsCookiePath); // Path cookie valid for
// Encrypt the ticket and store in a cookie
string CookieName = FormsAuthentication.FormsCookieName;
string CookieValue = FormsAuthentication.Encrypt(ticket);
cookie = new HttpCookie(CookieName, CookieValue);
// Set the cookie's expiration time to the tickets expiration time, plus a little to be sure.
// NB: the cookie is created and updated with "sliding" reset automatically
// if the SetAuth...() coockie call was used
// NB: Persistent is false, so this is a Session cookie without expiration
// that is deleted when the browser closes.
//if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration.AddMinutes(5);
}
Check if the session is still alive in a form.aspx.cs:
protected void Page_PreInit(object sender, EventArgs e)
{
// Load settings from session variabele
MySession = Session["MySession"] as ClSession;
// return to loginpage indien sessionvar = null
if (MySession == null)
Response.Redirect("~/SessionExpired.html"); // <<---after only 20 minutes!!??
return;
}
来源:https://stackoverflow.com/questions/38851190/session-data-lost-before-ticket-timeout