如何在.NET MVC 5中存储会话数据 [英] How to store session data in .NET MVC 5

查看:112
本文介绍了如何在.NET MVC 5中存储会话数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用HttpContext.ApplicationInstance.Context类通过Session函数存储会话数据吗? 还是有更好的方法可以做到这一点?

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?

推荐答案

通常,会话可以作为控制器操作中的属性来使用:

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

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

由于 Session 属性的类型为HttpSessionStateBase,可以在单元测试中更轻松地对其进行模拟.请不要使用静态HttpContext.Current.Session,如您在其他地方可能会看到的建议.

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.

如果您不在控制器动作中,则可以使用其Session属性访问HttpContextBase实例(几乎在MVC管道的每个部分中),以访问该会话.

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.

这篇关于如何在.NET MVC 5中存储会话数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆