Reputation: 7490
I've done quite a bit of testing on this, and I'm thoroughly confused. It seems ASP.NET will generate an ASP.NET_SessionId
cookie if the Session_Start
method in the MvcApplication
class is defined, even if I'm not using the Session
variable anywhere. That seems odd, considering there doesn't have to be anything in the method's body.
Example (Global.asax.cs):
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace MyApplication
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
private void Session_Start() { } // this is all it takes to generate a SessionId (?)
}
}
Now, I'm confused for multiple reasons:
How is the mere presence of the Session_Start
function enough to generate a SessionId? I'm not utilizing the Session
variable anywhere in the application, and the method is empty.
The Session_Start
method is private, and I'm obviously not calling it anywhere inside the class, so how does ASP.NET know when a session starts?
How does anything outside of this class even know the Session_Start
method exists, and to check for a SessionId cookie? It isn't a partial class, and it's explicitly marked private
.
I know these reasons sort of blend into one another, but I'm really at a loss as to how this works.
Upvotes: 6
Views: 22407
Reputation: 8485
Session_Start
is like an event handler for the application. When a new session is created, this method is called by the application. It does not create Session IDs, it is meant as a way for the developer to know when a user visits the site for the first time (that session). This can be used to run some initialization routines or tracking purposes (e.g., we had x number of unique sessions today).
What triggers the creation of the Session and SessionID is a user visiting a page that has session enabled-- ASP.NET will create the Session behind the scenes. The answer to this question has two ways of enabling session state for pages: Session state can only be used when enableSessionState is set to true either in a configuration
In summary:
in web.config, for all pages:
<system.web>
<pages enableSessionState="true" />
</system.web>
in your page.aspx, on a per-page basis (set it to false to turn it off on a per-page basis):
<%@Page enableSessionState="true">
Your web.config should also configure the SessionState mode. This is an example of using the server's memory to store session state:
<sessionState cookieless="false" mode="InProc" timeout="20" />
Upvotes: 7