ControllerContext.HttpContext.Session 和 HttpContext.Current.Session 有什么区别

发布于 2024-10-04 08:21:31 字数 553 浏览 0 评论 0原文

我正在使用一个可以伪造会话的示例。 它用于 mvc 控制器的单元测试。

在测试中,我创建一个控制器,然后执行以下操作:

FakeHttpContext  httpctx  = new FakeHttpContext(null,null,null,null,mSessionItems );
ControllerContext ctx2 = new ControllerContext(httpctx,new RouteData(), target);

其中 mSessionItems 是我的会话,target 是我的控制器实例

,事实上,当我在控制器中时阅读 this.ControllerContext.HttpContext.Session,我有一个会话,太棒了!

但是....我还在控制器外部读取了会话,并且在那里我使用了 HttpContext.Current.Session ,并且它是 null (或者实际上, HttpContext.Current )为空)。

所以我想知道,两者有什么区别?

i'm using an example in which i can fake the session.
It's for use in a unittest of a mvc controller.

In the test i create a controller and then i do this:

FakeHttpContext  httpctx  = new FakeHttpContext(null,null,null,null,mSessionItems );
ControllerContext ctx2 = new ControllerContext(httpctx,new RouteData(), target);

where mSessionItems is my session and target is my instance of a controller

and indeed, when i'm in a controller reading this.ControllerContext.HttpContext.Session, i have a session, great!

but.... i also read the session outside the controller, and there i use HttpContext.Current.Session, and that is null (or actualy, the HttpContext.Current is null).

So i wondered, what is the difference between the two?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

过气美图社 2024-10-11 08:21:31

ControllerContext.HttpContext 是抽象类型 HttpContextBase。此类型的默认实现 (HttpContextWrapper) 包装对 HttpContext 的访问。因此,当您创建假实现时,您将替换其与 HttpContext 的关系。假的实现不会为您创建真正的 HttpContext。

顺便提一句。您在哪里访问控制器外部的会话?你怎么知道会有当前的 HttpContext?

ControllerContext.HttpContext is of the abstract type HttpContextBase. Default implementation of this type (HttpContextWrapper) wraps access to HttpContext. So when you create the fake implementation you are replacing its relation to HttpContext. Fake implementation will not create real HttpContext for you.

Btw. where do you access the session outside controller? How do you know that there will be any current HttpContext?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文