How to Check whether Session is Expired or not in asp.net

前端 未结 8 2034
情话喂你
情话喂你 2020-12-03 01:03

I\'ve specified the session timeout in web.config file. When the session is timeout I\'m not getting redirect to the login page but I am getting an error saying object refer

相关标签:
8条回答
  • 2020-12-03 01:50

    I prefer not to check session variable in code instead use FormAuthentication. They have inbuilt functionlity to redirect to given LoginPage specified in web.config.

    However if you want to explicitly check the session you can check for NULL value for any of the variable you created in session earlier as Pranay answered.

    You can create Login.aspx page and write your message there , when session expires FormAuthentication automatically redirect to loginUrl given in FormAuthentication section

    <authentication mode="Forms">
      <forms loginUrl="Login.aspx" protection="All" timeout="30">
      </forms>
    </authentication>
    

    The thing is that you can't give seperate page for Login and SessionExpire , so you have to show/hide some section on Login.aspx to act it both ways.

    There is another way to redirect to sessionexpire page after timeout without changing formauthentication->loginurl , see the below link for this : http://www.schnieds.com/2009/07/aspnet-session-expiration-redirect.html

    0 讨论(0)
  • 2020-12-03 01:56

    Edit

    You can use the IsNewSession property to check if the session was created on the request of the page

    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"); 
             } 
          } 
       } 
    }
    

    pre

    Store Userid in session variable when user logs into website and check on your master page or created base page form which other page gets inherits. Then in page load check that Userid is present and not if not then redirect to login page.

    if(Session["Userid"]==null)
    {
      //session expire redirect to login page 
    }
    
    0 讨论(0)
提交回复
热议问题