为什么我的会话变量不提供建设控制器? [英] Why my session variables are not available at construction of a Controller?

查看:74
本文介绍了为什么我的会话变量不提供建设控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ASP.NET MVC试图获取存储在我的会话[对象名]从构造函数中,我看到会话尚未设置的信息时,但一旦控制器已建成则会话包含正确的信息。

Using ASP.NET MVC when trying to get the information stored on my Session["objectName"] from the constructor, I see that the Session has not been set yet, but once the controller has been constructed then the Session contains the right information.

public class ABCController : Controller
{
   public ABCController() { var tmp = Session["Whatever"]; } //This line is null
   //But I know it has information

   public ActionResult Index() { var tmp = Session["Whatever"]; } //This works fine
}

感谢

推荐答案

会议在HttpContext的发现。 HttpContext的被提供给控制器作为ControllerContext的一部分。由于ControllerContext不作为参数传递给构造函数,它是不可用的类已创建和ControllerContext已分配后,直到。它应该是可用的,然而,在控制器上的任何方法。我不知道你怎么能指望填充类的属性的的类的构造函数被调用(除非他们是静态类属性,但是这不是这里的情况)。

The session is found in the HttpContext. HttpContext is provided to the controller as part of the ControllerContext. Since a ControllerContext isn't passed as an argument to the constructor, it isn't available until after the class has been created and the ControllerContext has been assigned. It should be available, however, in any method on the controller. I'm not sure how you could expect the properties of a class to be populated before the class constructor is called (unless they're static class properties, but that's not the case here).

这篇关于为什么我的会话变量不提供建设控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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