when this object will be garbage-collected or destroyed.
When the session expires. The session state is configured in your web.config using the <sessionState>
node. You may take a look at the following overview
about sessions. By default ASP.NET stores session data in-memory. This means that if your application is running in a web farm you will have problems because the different nodes of this webfarm might not see the value that was stored on some other node. If you want to use sessions in such scenario you will have to configure an out-of-process session state such as StateServer
or SqlServer
. Another problem with the default InProc
session state mode is that if IIS decides to recycle your application you might loose the data that is stored inside. Yet another reason not use session at all or use an out-of-proc session storage.
So for example you could specify a timeout for your session like this:
<sessionState mode="InProc" timeout="20" />
The default value is 20 minutes. But once again it will depend on the mode you are using.
I know in another scripting language like PHP, I have to call
session_start() and session_end() in all of the files that needs use
of this similar session object data.
No need to worry about such things in ASP.NET MVC.
Now all this being said, I would recommend you not using any session at all. ASP.NET already provides you with the necessary mechanism to track authenticated users. You could use Forms Authentication
which is designed exactly for the purpose of securely tracking authenticated users.
So start by turning off the ASP.NET session:
<sessionState mode="Off" />
and then:
[Anonymous]
public ActionResult Login(LoginModel model)
{
// TODO: check credentials, ...
FormsAuthentication.SetAuthCookie(model.Username, false);
//something else
// finally redirect and inside the target controller action
// you will be able to retrieve the authenticated user
return RedirectToAction("SomeProtectedAction");
}
and then you could decorate protected controller actions that are accessible only by authenticated users with the [Authorize]
attribute and inside them retrieve the currently authenticated user:
[Authorize]
public ActionResult SomeProtectedAction()
{
string username = User.Identity.Name;
// something else ...
}