且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.Net MVC 控制器构造函数中的会话为空

更新时间:2023-02-25 16:45:56

Andrei 是对的 - 它是 null 因为在 ASP.NET MVC 框架下运行时,HttpContext(因此 HttpContext.Session)在控制器时未设置类的构造与您预期的一样,但稍后由 ControllerBuilder 类设置(注入").如果你想更好地理解生命周期,你可以下拉ASP.NET MVC框架(源码可用),或者参考:本页

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.

然而,正如 Andrei 所建议的,如果您的代码依赖于 Session,那么编写单元测试可能会很困难,所以也许您可以考虑将 Session 包装在一个帮助类中,然后可以将其换成不同的, 在单元测试下运行时的非网络版本,因此将您的控制器与网络分离.

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.