How to store session data in .NET MVC 5

19,361

Solution 1

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.

Solution 2

Yes, you can apply data into a Session by utilizing the HttpContext. You should be wary of such implementations though, Model View Controller is in nature stateless. The session though will dictate some form of state.

You'll have to account for that, otherwise you could potentially introduce a large quantity of orphaned session variables if they're not accounted for. Which could eat memory in your environment rapidly depending on your application.

If the application is small, you could easily do it with the following in your Controller:

HttpContext.Current.Session.Add("Title", "Data"); 
Share:
19,361
miguelbgouveia
Author by

miguelbgouveia

I am developer with 10 years of experience. Interested in open source and sharing ideas. Coding using TDD process.

Updated on June 04, 2022

Comments

  • miguelbgouveia
    miguelbgouveia almost 2 years

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

  • dey.shin
    dey.shin over 6 years
    Why should one use the Session property instead of HttpContext.Current.Session? I did a quick search on the difference, and I got this