C# – ASP.Net session start and end issue

asp.netciisnetvisual-studio-2008

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

Best Answer

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.