Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net session start and end issue

I am using ASP.Net + .Net 3.5 + VSTS 2008 + IIS 7.0 + C# to develop a web application. I am creating a very simple web application, and I just modified page_load, Session_Start and Session_End. Here are my code, my question is I find session ends message is written to file immediately after session start message. My test method is just open IE to access this page. I think session should last for a long time, like several mins. Why session ends so quickly? Why seesion ends even if I do not close the page?

protected void Page_Load(object sender, EventArgs e)
{
    Response.Write("Hello World! ");
    Session["SomeUserData"] = DateTime.Now;
}

protected void Session_Start(object sender, EventArgs e)
{
    using (TextWriter tw = new StreamWriter(@"C:\TestSession\bin\session.txt", true))
    {
        // write a line of text to the file
        tw.WriteLine(DateTime.Now + " Session Started.");
    }
}

protected void Session_End(object sender, EventArgs e)
{
    using (TextWriter tw = new StreamWriter(@"C:\TestSession\bin\session.txt", true))
    {
        // write a line of text to the file
        tw.WriteLine(DateTime.Now + " Session Ended.");
    }
}

I met with the same issue even if add Session manipulation code into Page_Load method, here is output file content, which you can see session ends event is called immediately after session start.

2010/7/15 0:11:14 Session Started.
2010/7/15 0:11:14 Session Ended.
2010/7/15 0:11:28 Session Started.
2010/7/15 0:11:28 Session Ended.

thanks in advance, George

like image 220
George2 Avatar asked Dec 29 '22 10:12

George2


2 Answers

If I remember correctly, you need to actually assign something to Session to activate it. Otherwise ASP.NET will regenerate a new session (new session id if you use fiddler to check) every time.

EDIT: Because session.txt is located inside the bin directory. Once you write to the bin directory the application will restart so the Session_End event fired immediately. Move session.txt out of bin directory to somewhere else will resolve your issue.

like image 143
airmanx86 Avatar answered Dec 30 '22 23:12

airmanx86


This kind of behaviour is sometimes caused by an overzealous anti-virus program. Try disabling the anti-virus and see if that helps. If it helped, then add the site's directory to the exclusion list.

Also closing the browser doesn't have any effect on your session either way.

like image 41
Johann Strydom Avatar answered Dec 30 '22 23:12

Johann Strydom