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
Use Session.Contents.Count
:
if (Session.Contents.Count == 0)
{
Response.Write(".NET session has Expired");
Response.End();
}
else
{
InitializeControls();
}
The code above assumes that you have at least one session variable created when the user first visits your site. If you don't have one then you are most likely not using a database for your app. For your case you can just manually assign a session variable using the example below.
protected void Page_Load(object sender, EventArgs e)
{
Session["user_id"] = 1;
}
Best of luck to you!
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.
I use the @Adi-lester answer and add some methods.
Method to verify if Session is Alive
public static void SessionIsAlive(HttpSessionStateBase Session)
{
if (Session.Contents.Count == 0)
{
Response.Redirect("Timeout.html");
}
else
{
InitializeControls();
}
}
Create session var in Page Load
protected void Page_Load(object sender, EventArgs e)
{
Session["user_id"] = 1;
}
Create SaveData method (but you can use it in all methods)
protected void SaveData()
{
// Verify if Session is Alive
SessionIsAlive(Session);
//Save Data Process
// bla
// bla
// bla
}
Check if it is null or not e.g
if(Session["mykey"] != null)
{
// Session is not expired
}
else
{
//Session is expired
}
this way many people detect session has expired or not. the below code may help u.
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");
}
}
}
}
}
Here I am checking session values(two values filled in text box on previous page)
protected void Page_Load(object sender, EventArgs e)
{
if (Session["sessUnit_code"] == null || Session["sessgrcSerial"] == null)
{
Response.Write("<Script Language = 'JavaScript'> alert('Go to GRC Tab and fill Unit Code and GRC Serial number first')</script>");
}
else
{
lblUnit.Text = Session["sessUnit_code"].ToString();
LblGrcSr.Text = Session["sessgrcSerial"].ToString();
}
}