Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

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 reference not set to an instance.

Can anyone tell me the solution for this?

like image 726
user1379439 Avatar asked May 07 '12 10:05

user1379439


People also ask

How check session expired in ASP.NET MVC?

In web applications, session holds the information of current logged-in users. So, if the session expires in 20 minutes, then it is redirected to login page. In that case, we need to check if session exists (not null) in every action/ every controller which requires authentication.

How session is expired?

If your Internet connection is unstable, periodically disconnecting and reconnecting, it can cause a website session to expire. When the Internet connection is lost the website connection can be terminated, resulting in a session expired message if you try to access any page after the Internet reconnects.

How can I see the session timeout of a website?

If you want to determine when the countdown for timeout starts, you can can go to the Logic tab, right-click on the Server Actions folder, select Add System Event and then On Begin Web Request. This will create an action that will run every time your module handles a new request.

What is ASP.NET session?

ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request.


2 Answers

You can check the HttpContext.Current.User.Identity.IsAuthenticated property which will allow you to know whether there's a currently authenticated user or not.

like image 90
Darin Dimitrov Avatar answered Sep 19 '22 23:09

Darin Dimitrov


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  } 
like image 31
Pranay Rana Avatar answered Sep 22 '22 23:09

Pranay Rana