miguelbgouveia miguelbgouveia - 1 year ago 136
C# Question

How to store session data in .net MVC 5

Can I use the HttpContext.ApplicationInstance.Context class to to store session data using the Session function?
Or there is a better way to do this?

Answer Source

Normally the session is available as a property in your controller actions:

public ActionResult Index()
{
    this.Session["foo"] = "bar";
    return View();
}

Since the Session property is of type HttpSessionStateBase it can be more easily mocked in a unit test. Please never use the static HttpContext.Current.Session as you might see suggested elsewhere.

If you are not inside a controller action you can access the session if you have an instance of HttpContextBase (which is almost in every part of the MVC pipeline) using its Session property.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download