The session works exactly the same as in Webforms. If you want to store simple information, use a form authentication cookie. If you want to save the contents of a shopping cart, a session is the place to go. I wrote a blog post about using a session with ASP.NET :
Suppose we want to save the whole variable in Session. We will create a wrapper around the Session variable, which will make it more pleasant:
:
public interface ISessionWrapper
{
int SomeInteger { get; set; }
}
HttpContext:
public class HttpContextSessionWrapper : ISessionWrapper
{
private T GetFromSession<T>(string key)
{
return (T) HttpContext.Current.Session[key];
}
private void SetInSession(string key, object value)
{
HttpContext.Current.Session[key] = value;
}
public int SomeInteger
{
get { return GetFromSession<int>("SomeInteger"); }
set { SetInSession("SomeInteger", value); }
}
}
GetFromSession SetInSession - , . SomeInteger .
( ASP.NET MVC):
public class BaseController : Controller
{
public ISessionWrapper SessionWrapper { get; set; }
public BaseController()
{
SessionWrapper = new HttpContextSessionWrapper();
}
}
Session, HttpContextSessionWrapper().
SessionWrapper ISessionWrapper Controller, HttpContext. , (int) Session [ "SomeInteger" ] SessionWrapper.SomeInteger. , ?
, Session, - BaseController, , .