如何使用MVC会话变量 [英] How to use Session Variable in MVC
问题描述
我已经声明Session变量,
保护无效的Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
INT TEMP = 4;
HttpContext.Current.Session.Add(_ SessionCompany,温度);
}
和想使用这个会话变量到我的控制器的行动,
公众的ActionResult指数()
{
VAR测试= this.Session [_ SessionCompany];
返回查看();
}
但我正在逐渐的异常当访问会话变量。
请帮我在这,我如何可以访问会话变量到我的控制器的动作。
我越来越像一个异常对象引用未设置为一个对象的Insatance
在的Application_Start
在Global.asax中的行
HttpContext.Current.Session.Add(_ SessionCompany,温度);
当用户对网页的请求启动该应用程序的线程不使用的请求线程。
这意味着当你在的Application_Start
,你不将它设置为任何用户设置。
您想设置在session_start
事件的会话。
编辑:
一个新的事件添加到您的名为文件的Global.asax.cs 在session_start
和的Application_Start
保护无效在session_start(对象发件人,EventArgs的发送)
{
INT TEMP = 4;
HttpContext.Current.Session.Add(_ SessionCompany,温度);
}
这应该解决您的问题。
I have declared Session variable in "Global.asax" file as,
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);
}
And want to use this Session Variable into My Controller's action as,
public ActionResult Index()
{
var test = this.Session["_SessionCompany"];
return View();
}
But I am Getting Exception While accessing the Session Variable. Please help me on this that How can I access the Session Variable into my controller's Action.
I am getting an Exception like
"Object Reference not set to an Insatance of an object"
in Application_Start
in Global.asax on line
HttpContext.Current.Session.Add("_SessionCompany",temp);
The thread that starts the Application is not the request thread used when the user makes a request to the web page.
That means when you set in the Application_Start
, you're not setting it for any user.
You want to set the session on Session_Start
event.
Edit:
Add a new event to your global.asax.cs file called Session_Start
and remove the session related stuff from Application_Start
protected void Session_Start(Object sender, EventArgs e)
{
int temp = 4;
HttpContext.Current.Session.Add("_SessionCompany",temp);
}
This should fix your issue.
这篇关于如何使用MVC会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!