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

use*_*439 27 c# asp.net

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

谁能告诉我这方面的解决方案?

Dar*_*rov 17

您可以查看该HttpContext.Current.User.Identity.IsAuthenticated属性,以便您了解是否有当前经过身份验证的用户.

  • 会话的到期是否完全与`IsAuthenticated`变为false同义? (6认同)
  • 无论是第一次访问者还是超时用户,`HttpContext.User.Identity`都将具有相同的值. (2认同)

Pra*_*ana 14

编辑

您可以使用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"); 
         } 
      } 
   } 
}
Run Code Online (Sandbox Code Playgroud)

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

if(Session["Userid"]==null)
{
  //session expire redirect to login page 
}
Run Code Online (Sandbox Code Playgroud)


Imr*_*zvi 8

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

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

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

<authentication mode="Forms">
  <forms loginUrl="Login.aspx" protection="All" timeout="30">
  </forms>
</authentication>
Run Code Online (Sandbox Code Playgroud)

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

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


小智 7

用途Session.Contents.Count:

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

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

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

祝你好运!


Adi*_*dil 6

检查它是否为空,例如

if(Session["mykey"] != null)
{
  // Session is not expired
}
else
{
  //Session is expired
}
Run Code Online (Sandbox Code Playgroud)