This is my base class for all pages except EndSession.aspx
override protected void OnInit(EventArgs e) {
base.OnInit(e);
if (Context.Session != null)
{
//check the IsNewSession value, this will tell us if the session has been reset.
//IsNewSession will also let us know if the users session has timed out
if (Session.IsNewSession)
{
//now we know it's a new session, so we check to see if a cookie is present
string cookie = Request.Headers["Cookie"];
//now we determine if there is a cookie does it contains what we're looking for
if ((null != cookie) && (cookie.IndexOf("ASP.NET_SessionId") >= 0) )//&& !Request.QueryString["timeout"].ToString().Equals("yes"))
{
//since it's a new session but a ASP.Net cookie exist we know
//the session has expired so we need to redirect them
Response.Redirect("EndSession.aspx?timeout=yes");
}
}
}
}
But on EndSession I try to navigate back to, say default.aspx, and then this code above just redirects be back to EndSession.aspx.
So for better clarification:
Step 1: Go to mypage.aspx
Step 2: Wait for timeout
Step 3: try to navigate away
Step 4: get redirected to EndSession.aspx
Step 5: try to navigate away
Step 6: GoTo set 4
Setp 6 should be actually being able to navigate away...
(if needed pelase ask for further clarification)
Any ideas?
THANKS!!!
I got rid of the basepage that I had originally.
Put this in the Session_Start of Global.asax
void Session_Start(object sender, EventArgs e)
{
string cookie = Request.Headers["Cookie"];
// Code that runs when a new session is started
if ((null != cookie) && (cookie.IndexOf("ASP.NET_SessionId") >= 0))//&& !Request.QueryString["timeout"].ToString().Equals("yes"))
{
if(Request.QueryString["timeout"] == null || !Request.QueryString["timeout"].ToString().Equals("yes"))
Response.Redirect("Default.aspx?timeout=yes");
}
}
Put this on the Defualt.aspx page:
if (!IsPostBack)
{
if (Request.QueryString["timeout"] != null && Request.QueryString["timeout"].ToString().Equals("yes"))
{
Response.Write("<script>" +
"alert('Your Session has Timedout due to Inactivity');" +
"location.href='Default.aspx';" +
"</script>");
}
}
This solution works even when the timeout occurs on the Default.aspx page
The discusion for the solution I used is posted here: How to stop basepage from recursivly detecting session timeout
Related
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to Check whether Session is Expired or not in asp.net
What is the best way for a page to detect if a session has timed out in the code behind?
I found the below code in a blog (http://mattslay.com/detecting-session-timeout-in-asp-net/). Is is ok or is there a better way?
if (Context.Session != null && Context.Session.IsNewSession)
{
string cookieHeader = Page.Request.Headers["Cookie"];
if ((null != cookieHeader) && (cookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
return true; // timeout occured
else
return false;
}
I suggest you to treat this treatment in your Global.asax file
void Session_End(object sender, EventArgs e)
{
//Here you execute your treatments about end session
}
Link : http://msdn.microsoft.com/en-us/library/system.web.sessionstate.sessionstatemodule.end.aspx
i search google and found many answers for detecting session expiry programmatically. this is code which i saw everyone use it
global.asax
---------------
protected void Session_Start(object src, EventArgs e)
{
if (Context.Session != null && Context.Session.IsNewSession)
{
string sCookieHeader = Request.Headers["Cookie"];
if (null != sCookieHeader && sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0)
Response.Redirect("/Session/Timeout");
}
}
i have few question on the above code
1) when session expire then how Context.Session will not be null?
2) what is the meaning of this line Request.Headers["Cookie"];
looking for good discussion. thanks
You can use the Session_End method in global.asax file
void Session_End(Object sender, EventArgs E) {
// Clean up session resources
}
1) when session expire then how Context.Session will not be null?
Your code triggers when a user comes back to the server with an expired session.
The session object in this code is the new empty session which is beginning.
Remember you are in Session_Start, not in Session_End.
2) what is the meaning of this line Request.Headers["Cookie"];
The cookie contains the session's id. If a user is requesting a ressource, providing a session id, and Session_start is triggered, that almost certainly means that the session id refers to an expired session object. A specific message is then displayed to the user.
I have a Catcha value( Security Code ) that is store in Session on PageLoad and that is going to be used when user clicks the search button. If the User is IDLE for more than 20 Min the value of Session is get expired. And when user clicks on Search Button. It Throws error " Object Reference Not Set To an Instance of an Object".
On PageLoad:
if (!IsPostBack)
{
Session["CaptchaImageText"] = new RandomGen().GenerateRandomCode();
}
On SearchButtonClick event:
if (SecurityCodeTextBox.Text.Trim() == Session["Captcha"].ToString())
{
return true;
}
else
{
return false;
}
Here i get error "Object Reference Not Set To an Instance of an Object".
i have also checked wheather the Session["Captcha"]!= null. But still it shows the same error.
How to Redirect or show a message that "Session Timeout !Visit again" and close the Browser.
Thanks in Advance!
Your code looks like you're inconsistent with your Session variable naming (I'm a strong proponent of constants for these).
That being said, the easiest way to handle your situation is
private void Page_Load(object sender, System.EventArgs e)
{
Response.AddHeader("Refresh",Convert.ToString((Session.Timeout * 60) + 5));
if( string.IsNullOrEmpty(Session["Captcha"] as string) )
{
Server.Transfer("RedirectPage.aspx");
}
}
That will cause a page redirect on session expiration.
TO close the browser, you need a client-side script... there is no way to do it by server-side, so, you can generate some javascript calling window.close();. For th message error, check if the Session[] is not null, if you call some method of this and it's null, you will get this kind of exception. Try something like this:
if (Session["Captcha"] == null)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Session Timeout! Visit again.'); window.close();", true);
return false;
}
return (SecurityCodeTextBox.Text.Trim() == Session["Captcha"].ToString());
I'm using VS2010 and created a simple asp. web forms application, using Development Server to test it.
I try to store user data - queried from sql server - in the session, since I don't want to access database in every request. I'm using the 'Application_AuthenticateRequest' and the 'Session_Start' methods.
First round:
AuthenticateRequest called. The following code ran:
public static void Initialize(string login_name, bool force_refresh)
{
HttpSessionState Session = HttpContext.Current.Session;
object o = Session == null ? null : Session["EMPLOYEE_DATA"];
if (force_refresh || o == null || o.GetType() != typeof(Employee) || (o as Employee).login_name!= login_name)
{
_current = UIManager.GetEmployee(login_name);
if (Session != null)
{
Session["EMPLOYEE_DATA"] = _current;
}
}
else
{
_current = (Employee)o;
}
}
The _current variable is a private static field published through a static property.
In the first round the Session is null, and I think it's ok because the Session_Start not called yet.
The Session_Start looks like this:
protected void Session_Start(object sender, EventArgs e)
{
Session["EMPLOYEE_DATA"] = EmployeeFactory.Current;
}
In the next round the Session_Start is not called of course but in the AuthenticateRequest I can't access to the session. The HttpContext.Current.Session is null and the this.Session reference throw a HttpException says the "Session state is not available in this context".
However I can access the Session from any of the page_load events but it's a bad practice I think that I put authentication every page_load.
Any idea how can I access to the Session?
Thanks for advice,
Péter
You're not able to use Session on the Application_AuthenticateRequest becauase it's not bound at that moment.
I think you're able to use the event Application_AcquireRequestState.
try to use the below code in page_Load
Response.AppendHeader("Refresh", Convert.ToString(Session.Timeout * 15) + ";
URL=SessionExpPage.aspx");
I'm recording the session start times from when people log into my .NET 2.0 web application, but I'd also like to record the Session ID. Can someone give me some example code on how to accomplish this (how to access the Session ID from within the Global.ASAX).
If you need any additional info just let me know.
HttpContext.Current.Session.SessionID
Edit to show null test:
if ((HttpContext.Current != null) && (HttpContext.Current.Session != null) {
id = HttpContext.Current.Session.SessionID
}
You can get at it quite simply with HttpContext.Current.Session.SessionId as you probably already know. You need to be on or after Application_AcquireRequestState before the session state has been loaded, and session state is also only loaded when the requested resource implements IRequiresSessionState. You can see a list of all the events in global.asax here: https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5771721.html and read more about IRequiresSessionState here: http://msdn.microsoft.com/en-us/library/system.web.sessionstate.irequiressessionstate.aspx
Write to the session the datetime and sessionid at the moment of the first request following ASP.NET's identifying the user's session.
protected void Application_PreRequestHandlerExecute(object sender, EventArgs eventArgs) {
var session = HttpContext.Current.Session;
if (session != null) {
if (session["foo"] == null) {
session["foo"] = DateTime.Now.Ticks + "|" + session.SessionID;
}
}
}