使用此web.config元素设置会话状态超时
<sessionState mode="InProc" cookieless="false" timeout="120" />
使用此web.config元素配置表单身份验证
<system.web>
<authentication mode="Forms">
<forms loginUrl="Login.aspx"
protection="All"
timeout="30"
name=".ASPXAUTH"
path="/"
requireSSL="false"
slidingExpiration="true"
defaultUrl="default.aspx"
cookieless="UseDeviceProfile"
enableCrossAppRedirects="false" />
</authentication>
</system.web>
每个元素中指定的超时之间有什么区别?如果两者不同,它将如何运作?
答案 0 :(得分:58)
每当新用户访问网站时,会话就会启动,无论他们是否是匿名用户。身份验证与Session几乎没有关系。
身份验证超时是身份验证Cookie在用户浏览器上有用的时间。一旦cookie过期,他们必须重新进行身份验证才能访问站点上受保护的资源。
因此,如果Session在Authentication cookie之前超时 - 它们仍然经过身份验证,但是它们的所有会话变量都会消失,并且如果您在检查由于缺少会话而导致的空值和其他条件时没有受到约束,则可能会导致您的网站出错
如果身份验证在会话之前超时,那么它们的所有会话变量仍然存在,但在重新登录之前,它们将无法访问受保护的资源。
答案 1 :(得分:1)
正如所料。
e.g。如果您的会话在20分钟后超时,您的会话变量将会丢失。 但是用户可以访问受身份验证保护的页面。
如果身份验证超时,则用户无法访问其保护的页面,并且会话状态无关紧要。
答案 2 :(得分:-3)
会话超时值必须小于FormsAuthentication超时时间。因为可以因为某个原因而删除会话,所以方案不起作用。
如果会话超时,请检查FormsAuthentication Ticket。如果票证有效且没有超时,则在您的登录页面重新生成会话(在您的web.config文件中定义为FormsAuthentication设置的LoginUrl参数)。
如果FormsAuthentication超时,ASP.NET FormsAuthentication会自动将用户重定向到Login Page,用户必须再次登录。
不要忘记,在票证超时时,FormsAuthentication会自动将用户重定向到登录页面。
其实我更喜欢这种结构:
在BasePage.cs的Page_Init中检查Session。如果会话已过期;将用户重定向到登录页面。
if(Session [“UserId”] == null)Response.Redirect(“Login.aspx”,true);
在Login.aspx的Page_Load中,正确检查Session和FormsAuthentication Ticket时间。
//User already have a session; redirect user to homepage.
if (SessionHandler.UserId != 0)
Response.Redirect("HomePage.aspx");
else
{
//Session is killed; check Ticket is Valid or not
if (Context.User.Identity != null && Context.User.Identity.IsAuthenticated)
{
//Use Value of the FormsAuthentication
var customDataToCheck = Context.User.Identity.Name;
//Use value to check user is exist really and check db for user's session
var user = CheckUserData(customDataToCheck);
if (user != null)
{
//Start Session here
SessionHandler.StartSession(user);
//Redirect user to page what you want.
Response.Redirect("HomePage.aspx?ref=regenerated_session");
}
}
}
使用FormsAuthentication创建cookie。
if(username ==“testuser”&amp;&amp; password ==“testpassword”)
{
//用户数据将被写入cookie,存储您可以检查用户是否有效的用户数据(例如Username或UserId)。
System.Web.Security.FormsAuthentication.SetAuthCookie(“testUserData”,keepMeSignedInCheckBox.Checked);
的Response.Redirect( “HomePage.aspx”);
}