How to store session data in .NET MVC 5

2019-04-17 14:09发布

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?

2条回答
Deceive 欺骗
2楼-- · 2019-04-17 14:27

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"); 
查看更多
爷、活的狠高调
3楼-- · 2019-04-17 14:33

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.

查看更多
登录 后发表回答