ASP.NET SessionState TimeOut not working - c#

I want my web page to close when SessionState timeout occures. This is my code in my web config:
<system.web>
<sessionState timeout="1" mode="InProc"/>
</system.web>
I set to 1 minute for testing purposes. The following is my Global.asax code:
protected void Session_End(object sender, EventArgs e)
{
Response.Redirect("~/LogOut.aspx");
}
I put a label on one of the pages in order to check the session timeout, this is the code in the Page_Load event:
lblSession.Text = "SESSION TIME: " + Session.Timeout.ToString();
When I enter the site and come to this page the label shows SESSION TIME: 1, but after 1 minute I don't get redirected to the LogOut page and the present page is still fully active and working, apparently meaning that the session has not been terminated.
I am working in Visual Studio 2008 thru the development server so suggestions I've seen relating to IIS settings don't seem to be relevant at this stage.
Please help!

HTTP is a request / response protocol. There is no persistent connection between the browser and the server. The code in Session_End thus effectively does nothing — it can't tell the browser to do anything.
You would need to make a (client-side) JavaScript timer and actively load the logout page right before the session timeout elapses.

Session_End in my experience gets called on the first postback (could be implemented via a client-side Timer) after the timeout occurred - whenever that might be... if the user just closes the browser this event may never be called (except for the case you made a specific JS handler unload to do the postback in that situation).
For some information see:
http://justgeeks.blogspot.com/2008/07/aspnet-session-timeouts.html
http://www.highoncoding.com/ArticleDetails.aspx?articleID=108
http://forums.asp.net/t/1271309.aspx/2/10
http://www.codeproject.com/KB/aspnet/PageTracking.aspx
http://p2p.wrox.com/asp-pro-code-clinic/1648-session_onend-not-firing.html
http://aspalliance.com/1182_Troubleshooting_Session_Related_Issues_in_ASPNET.all

This doesn't seem to be the correct way of testing your session timeout. Try putting something in the session variables. Don't touch the page for another couple of minutes, and try reading it back from Session. If your session is alive, you should be able to see the variables, else... you won't.
Learn more about session and troubleshooting session... http://aspalliance.com/1182_Troubleshooting_Session_Related_Issues_in_ASPNET

Related

Testing session timeout in C#

I have my session timeout set to 1 in web.config.
I wanted to check whether session start and end occurs as expected, so I had this in my global.asax.cs-
//In Session_Start
Response.Write("<script>alert('session started');</script>");
//In Session_End
Response.Write("<script>alert('session ended');</script>");
I get the alert when session starts but not when it ends. When I put breakpoints, I see that the line is executed in Session_End but there is no alert on the screen.
This is my first time working with sessions and even though I was able to test the functions another way, I am curious why it did not show the alert.
Thanks in advance.
I know you are looking to write to the response and not redirect but have a look at this: Redirecting to another page on Session_end event
another-page-on-session-end-event
Session_End is called when the session ends - normally 20 minutes after the last request (for example if browser is inactive or closed).
Since there is no request there is also no response.
This would strongly suggest that you cannot write to the response... because there isn't one.

How can i close the session after x time

In ASP.NET on IIS 7.5, how can I close the session after an amount of time (lets say 5 hours), even if the user is still working and there is no idle time?
Is there a property in IIS or should I do it in code?
Have you tried the web.config?
<configuration>
<system.web>
<sessionState
mode="InProc"
cookieless="true"
timeout="30" />
</system.web>
</configuration>
I'm also assuming you have a basic site with no load balancing or session state servers. Those require different approaches.
I haven't tried such a solution before but here's what come into mind :
In your global.asax handle SessionStart and when a new session is started create a new (Asynchronous )Task that starts a timer (a timer that execute once after 5 hours and calls Session.Abandon() :
Something like this :
new Task(()=>{
var timer=new Timer{Interval=DateTime.Now.AddHours(5), Elpased+=(obj,args)=>{
session.Abandon();
((Timer)obj).Stop();
((Timer)obj).Dispose();
}
}).Start()
As I told you I haven't test it and since everything is working asynchronously here it might led to unknown situations.
(BTW as far as I know timer will already run in another thread so no Task is needed :) )
Update
OK, It seems that we can't hold a reference to a HtmlStateSession. Thus here's another approach that I think it can help: In this approach we hold a registery of session id and start time of each session in a static dictionary and when a request begins we check if its session (according to its session id) has been out there more than 5 hours and if that is the case we Abonden the session.(and remove the id from dictionary of course)
There's no need to have thousands of timers this way and we don't expire the sessions right away but we wait until the next time that user sends us a request.
What about setting up windows task scheduler to run an aspx page that will check how long the user is logged in and according to it, to decide if to close the session or not.
(You can save in your database, a log-in time for each user).

.net web forms application keeps logging out users

I have a web forms application that I tested and works good locally.
When i upload it to a web server that hosts my site, it often just logs out users(they get redirected to the Account/Login.aspx page).
It doesn't produce an error in application so i dont know how to debug it properly but i think that it happens during page load event because users get logged out of the application sometimes(not always) after they make some changes, but the changes stay saved.
I think for some reason my session variable that keeps the login of the user gets reset.
If you have an idea or point me in some direction what and how i can investigate this issue, i would really appreciate it.
This is my code that runs on page load in my site Master.cs, maybe it helps:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["UserId"] == null)
{
Response.Redirect("~/Account/login.aspx");
}
if (!Session["Role"].ToString().Equals("Coach"))
{
if (Session["Role"].ToString().Equals("Administrator"))
Response.Redirect("~/AdminForm/AdminHome.aspx");
if (Session["Role"].ToString().Equals("User"))
Response.Redirect("~/Form/Progress.aspx");
}
}
}
Thank You!
Did you set the timeout in your web.config file?
system.web>
<authentication mode="Forms">
<forms timeout="50000000" slidingExpiration="true"/>
</authentication>
</system.web>
If you users are on the site for more than 20 minutes it will log out. You can try web.config or IIS settings it will not help.
I found the best way to handle this is to use a KeepAlive page in and hidden iFrame that posts back to the server every 18 minutes. This will keep the worker process running and the site will never time out.
I have used this method on Internally Facing sites since the end users want to be on the site 8 to 5 without getting logged out.
Sample project at this link

Session ends randomly after redirect

I have a strange problem in ASP .NET MVC 4. In AccountController I am doing redirects on certain actions and put data into TempData (which is stored in Session) before that:
[AllowAnonymous]
public ActionResult Activate(string token)
{
new CustomSignupService().Activate(token);
TempData["Message"] = "User was successfully confirmed";
return RedirectToAction("Message", "Home")
}
Now I know I could just return shared Message view in this case, but this is just a code sample to reproduce the problem.
CustomSignupService.Activate does a db lookup via NHibernate and updates user in transaction (user activation). Sometimes (lets say 1/5 tries in 5 minutes) TempData does not make it throught the redirect, so I added logging into Session_End and noticed that session ends when RedirectToAction is invoked. Right after that Session_Start is invoked but of course TempData is gone.
Session has default timeout (20min) and controllers use SessionStateBehavior.ReadOnly
Any ideas?
UPDATE
Step 1: It's not Application Pool recycling (I turned on all General Recycle Event Log entries on Application pool and checked event log, after session restarts but recycle is not causing it)
I had a problem with Session being lost. I used Fiddler and noticed that there was a duplicate ASP.NET session cookie with a blank value. I don't know how it got there. So a new session was created on every request. I deleted that duplicate cookie and the problem was solved.
Other unlikely reasons are:
IIS process recycle
Session.abandon being called
modifying bin folder or web.config causing app restart
Check out this page:
Losing Session State
I don't know ASP.NET MVC but in the dark centuries I used ASP.NET without MVC. I struggled several times with unexpected session ends. Most of the time it was caused by some simple things which are described in the article http://www.c-sharpcorner.com/uploadfile/technoNet/session-timeouts-causes-and-remedies/
Sometimes the server has entries in the event log that gives you a little bit more information.
And some other solutions might be
ASP.NET Session ending abruptly
random IIS session timeout

Session clears ends when debugging ASP.NET but works fine on the dev and test server

I'm having a strange issue where the session ends after a postback when I debug it in visual studio 2010.
I store a variable in a session on the first page. It keeps its value in the next page but after that it gets lost. It returns a null value. The strange thing is when i copy the exact code to the dev or test servers, it works fine...
Any ideas what could be happening? Thanks.
UPDATE
The code is fairly simple. I have a default.aspx page where I'm setting a session variable:
HttpContext.Current.Session["PurchaseOID"] = purchaseOID;
When I click 'Next' the Default.aspx page redirects it to a Information.aspx page. Additional user information is gathered on this page (using DevExpress controls). When I click 'Next' on this page the session variable "PurhcaseOID" returns null on page load.
protected void Page_Load(object sender, EventArgs e)
{
if(HttpContext.Current.Session["PurchaseOID"] == null){
throw new Exception("error!");
}
}
Whats strange is, the Session is kept when the page is first loaded. But on postback, it loses its variables. Also, this is something that JUST started happening. I've been working on this code for a month or so and it's been working fine. When I deploy this exact code to our dev or test server, it works fine.
I'm debugging this in Cassini. Help would be greatly appreciated, thanks!
Shahzad Chaudhary
When you are testing do you have cookies disabled? I ask because the session id is stored in a cookie unless you are using cookieless sessions (rare). So if in your test environment you have cookies turned off in your browser then it will not be able to get the session values. I don't believe it throws any error when storing them though.
I figured it out, it was a stupid mistake. The change was happening in the Global.asax Application_Error method. For some reason when I put a breakpoint there it wouldn't hit.
When local debug, just set in web.config
<sessionState cookieless="true" />

Categories