ControllerContext.HttpContext.Session 和 HttpContext.Current.Session 有什么区别
我正在使用一个可以伪造会话的示例。 它用于 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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?