如何在MVC中使用会话变量

Rah*_*hul 14 c# asp.net-mvc session asp.net-mvc-3 asp.net-mvc-4

我在"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);
        }
Run Code Online (Sandbox Code Playgroud)

并希望将此会话变量用于我的控制器的操作,

 public ActionResult Index()
        {
            var test = this.Session["_SessionCompany"];
            return View();
        }
Run Code Online (Sandbox Code Playgroud)

但是我在访问会话变量时遇到异常.请帮我解决这个问题,如何将会话变量访问到我的控制器的Action中.

我正在一个异常就像 "Object Reference not set to an Insatance of an object"Application_Start上线的Global.asax

HttpContext.Current.Session.Add("_SessionCompany",temp);
Run Code Online (Sandbox Code Playgroud)

Phi*_*ill 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);
}
Run Code Online (Sandbox Code Playgroud)

这应该可以解决您的问题.