我在"Global.asax"文件中声明了Session变量,
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); int temp=4; HttpContext.Current.Session.Add("_SessionCompany",temp); }
并希望将此会话变量用于我的控制器的操作,
public ActionResult Index() { var test = this.Session["_SessionCompany"]; return View(); }
但是我在访问会话变量时遇到异常.请帮我解决这个问题,如何将会话变量访问到我的控制器的Action中.
我正在一个异常就像
"Object Reference not set to an Insatance of an object"
在Application_Start
上线的Global.asax
HttpContext.Current.Session.Add("_SessionCompany",temp);
Phill.. 21
启动Application的线程不是用户向Web页面发出请求时使用的请求线程.
这意味着当您设置时Application_Start
,您不会为任何用户设置它.
您想要在Session_Start
事件上设置会话.
编辑:
将新事件添加到您调用的global.asax.cs文件中,Session_Start
并从中删除与会话相关的内容Application_Start
protected void Session_Start(Object sender, EventArgs e) { int temp = 4; HttpContext.Current.Session.Add("_SessionCompany",temp); }
这应该可以解决您的问题.
启动Application的线程不是用户向Web页面发出请求时使用的请求线程.
这意味着当您设置时Application_Start
,您不会为任何用户设置它.
您想要在Session_Start
事件上设置会话.
编辑:
将新事件添加到您调用的global.asax.cs文件中,Session_Start
并从中删除与会话相关的内容Application_Start
protected void Session_Start(Object sender, EventArgs e) { int temp = 4; HttpContext.Current.Session.Add("_SessionCompany",temp); }
这应该可以解决您的问题.