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

查看:31
本文介绍了如何在 .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天全站免登陆