在ASP.Net MVC控制器构造空会话 [英] Session null in ASP.Net MVC Controller Constructors

查看:124
本文介绍了在ASP.Net MVC控制器构造空会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么是空会话在控制器的构造函数?它可以从操作方法进行访问。 presumably,因为MVC框架的路由负责newing-了一个控制器,它只是还没有(重新)初始化会话在这一点上。

Why is Session null in the constructors of Controllers? It can be accessed from Action methods. Presumably, because the MVC Routing framework is responsible for newing-up a Controller, it just hasn't (re-)instantiated the Session at that point.

有谁并知道这是由设计,如果是这样,为什么?

Does anyone know if this is by design and, if so, why?

[我设法通过使用延迟加载模式来规避这个问题。]

[I have managed to circumvent the problem by using a Lazy Loading Pattern.]

推荐答案

安德烈是正确的 - 因为ASP.NET MVC框架,HttpContext的下运行时(并因此HttpContext.Session)未设置当控制器为null类如池莉构建你所期望的,但它设置(注入),后来被ControllerBuilder类类。如果你想更好地理解生命周期的,你可以拉下ASP.NET MVC框架(提供源代码),或者参考:的this

Andrei is right - it is null because when running under the ASP.NET MVC framework, the HttpContext (and therefore HttpContext.Session) is not set when the controller class is contructed as you might expect, but it set ("injected") later by the ControllerBuilder class. If you want a better understanding of the lifecycle you can either pull down the ASP.NET MVC framework (the source is available), or refer to: this page

如果您需要访问会话再一个办法是重写OnActionExecuting的方法有访问它,因为这将是可用到那个时候。

If you need to access the Session then one way would be to override the "OnActionExecuting" method and access it there, as it will be available by that time.

不过,正如安德烈是暗示,如果你的code是依赖于会话那么它可能很难编写单元测试,所以也许你可以考虑然后可以换出一个辅助类包装会话对于不同的,非Web版本下的单元测试运行时,所以去耦合控制器从网络。

However, as Andrei is suggesting, if your code is reliant on the Session then it could potentially be difficult to write unit tests, so perhaps you could consider wrapping the Session in a helper class which can then be swapped out for a different, non-web version when running under unit tests, therefore de-coupling your controller from the web.

这篇关于在ASP.Net MVC控制器构造空会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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