如何在asp.net中检查会话是否过期

我在web.config文件中指定了会话超时。 当会话超时时,我没有重定向到登录页面但是我收到错误,说对象引用没有设置为实例。

谁能告诉我解决方案呢?

您可以检查HttpContext.Current.User.Identity.IsAuthenticated属性,该属性将允许您知道是否存在当前经过身份validation的用户。

编辑

您可以使用IsNewSession属性来检查会话是否是根据页面请求创建的

 protected void Page_Load() { if (Context.Session != null) { if (Session.IsNewSession) { string cookieHeader = Request.Headers["Cookie"]; if ((null != cookieHeader) && (cookieHeader.IndexOf("ASP.NET_SessionId") >= 0)) { Response.Redirect("sessionTimeout.htm"); } } } } 

当用户登录到网站时,将userid存储在会话变量中,并检查您的母版页或其他页面inheritance后创建的基页表单…并在页面加载中检查用户ID是否存在,如果不是重定向到登录页面

 if(Session["Userid"]==null) { //session expire redirect to login page } 

我不想在代码中检查会话变量而是使用FormAuthentication。 它们具有内置的function,可以重定向到web.config中指定的给定LoginPage。

但是,如果要显式检查会话,则可以检查先前在Pranay回答时在会话中创建的任何变量的NULL值。

当会话到期时,您可以创建Login.aspx页面并在那里编写消息FormAuthentication会自动重定向到FormAuthentication部分中给出的loginUrl

     

问题是你无法为Login和SessionExpire提供单独的页面,因此你必须在Login.aspx上显示/隐藏某些部分以便双向操作。

还有另一种方法可以在超时后重定向到sessionexpire页面而不更改formauthentication-> loginurl,请参阅以下链接: http : //www.schnieds.com/2009/07/aspnet-session-expiration-redirect.html

使用Session.Contents.Count

 if (Session.Contents.Count == 0) { Response.Write(".NET session has Expired"); Response.End(); } else { InitializeControls(); } 

上面的代码假定您在用户首次访问您的网站时至少创建了一个会话变量。 如果您没有,那么您很可能没有为您的应用使用数据库。 对于您的情况,您可以使用下面的示例手动分配会话变量。

 protected void Page_Load(object sender, EventArgs e) { Session["user_id"] = 1; } 

祝你好运!

检查它是否为空,例如

 if(Session["mykey"] != null) { // Session is not expired } else { //Session is expired } 

我使用@Adi-lester答案并添加一些方法。

validation会话是否活跃的方法

 public static void SessionIsAlive(HttpSessionStateBase Session) { if (Session.Contents.Count == 0) { Response.Redirect("Timeout.html"); } else { InitializeControls(); } } 

在页面加载中创建会话变量

 protected void Page_Load(object sender, EventArgs e) { Session["user_id"] = 1; } 

创建SaveData方法(但您可以在所有方法中使用它)

 protected void SaveData() { // Verify if Session is Alive SessionIsAlive(Session); //Save Data Process // bla // bla // bla } 

这种方式很多人检测到会话已经过期或没有。 以下代码可以帮助你。

 protected void Page_Init(object sender, EventArgs e) { if (Context.Session != null) { if (Session.IsNewSession) { HttpCookie newSessionIdCookie = Request.Cookies["ASP.NET_SessionId"]; if (newSessionIdCookie != null) { string newSessionIdCookieValue = newSessionIdCookie.Value; if (newSessionIdCookieValue != string.Empty) { // This means Session was timed Out and New Session was started Response.Redirect("Login.aspx"); } } } } } 

这里我正在检查会话值(前一页的文本框中填写了两个值)

 protected void Page_Load(object sender, EventArgs e) { if (Session["sessUnit_code"] == null || Session["sessgrcSerial"] == null) { Response.Write(""); } else { lblUnit.Text = Session["sessUnit_code"].ToString(); LblGrcSr.Text = Session["sessgrcSerial"].ToString(); } }