Detecting ASP.NET Session Timeouts
public class basePageSessionExpire : System.Web.UI.Page
{
public basePageSessionExpire()
{
}
override protected void OnInit(EventArgs e)
{
base.OnInit(e);
if (Context.Session != null)
{
if (Session.IsNewSession)
{
string szCookieHeader = Request.Headers[“Cookie”];
if ((null != szCookieHeader) && (szCookieHeader.IndexOf(“ASP.NET_SessionId”) >= 0))
{
Response.Redirect(“sessionTimeout.htm”);
}
}
}
}
}
How to create session variable which allows you to access your session properties in a type-safe way from any class
public class SessionHandler
{
private static string _userid;
private static string _menuid;
private SessionHandler() { }
public static SessionHandler Current
{
get
{
SessionHandler session =
(SessionHandler)HttpContext.Current.Session[“__MySession__”];
if (session == null)
{
session = new SessionHandler();
HttpContext.Current.Session[“__MySession__”] = session;
}
return session;
}
}
public string userid
{
get { return _userid; }
set { _userid = value; }
}
}
access values of session variables like this
SessionHandler.Current.userid
How to fetch the value from the session variable when the page is inherits from the non-page class.
Sometime you want to perform some task on page load on every page.
instead of call a function on each page. you can make a class and inherits all the pages from that class.
lets say you have a page Menu1.aspx.cs.
public partial class Menu1 : System.Web.UI.Page
{
}
replace the above line with
public partial class Menu1 : securepage
{
}
Now, create a securepage.cs
and inherits that class from System.Web.UI.Page
public class securepage : System.Web.UI.Page
{
public securepage()
{
}
}
Now if you want to access the session variable you have to write in the constructor.
like
public securepage()
{
string k=HttpContext.Current.Session[“menuid”].ToString();
}
it will generate error, because you cannot access session before page load.
the solution of above problem is:
create a page load function for that page.
public securepage()
{
base.Load += new EventHandler(securepage_Load);
}
private void securepage_Load(object sender, EventArgs e)
{
string k=HttpContext.Current.Session[“menuid”].ToString();
}