如何在MVC中使用会话变量
我在“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(); }
但是我在访问会话变量时遇到exception。 请帮我解决这个问题,如何将会话变量访问到我的控制器的Action中。
我在Global.asax中的Application_Start
中获得了一个exception,例如"Object Reference not set to an Insatance of an object"
HttpContext.Current.Session.Add("_SessionCompany",temp);
启动Application的线程不是用户向Web页面发出请求时使用的请求线程。
这意味着当您在Application_Start
设置时,您不会为任何用户设置它。
您想在Session_Start
事件上设置会话。
编辑:
将新事件添加到名为Session_Start
的global.asax.cs文件中,并从Application_Start
删除与会话相关的内容
protected void Session_Start(Object sender, EventArgs e) { int temp = 4; HttpContext.Current.Session.Add("_SessionCompany",temp); }
这应该可以解决您的问题。
您不应该在Application_Start()中设置会话变量,因为当应用程序在IIS中启动时,该方法仅被调用一次。 它不是基于会话的。
另外,我假设你的控制器有一个Session属性? 你准确设置好了吗?
使用HttpContext.Current.Session["_SessionCompany"]
而不是this.Session["_SessionCompany"]
– 这应该有效。
在控制器中,您可以像这样访问..
YourControllerID.ControllerContext.HttpContext.Session [ “_ SessionCompany”]
使用这个助手类:
namespace Projectname.UI.HtmlHelpers { //[DebuggerNonUserCodeAttribute()] public static class SessionHelper { public static T Get(string index) { //this try-catch is done to avoid the issue where the report session is timing out and breaking the entire session on a refresh of the report if (HttpContext.Current.Session == null) { var i = HttpContext.Current.Session.Count - 1; while (i >= 0) { try { var obj = HttpContext.Current.Session[i]; if (obj != null && obj.GetType().ToString() == "Microsoft.Reporting.WebForms.ReportHierarchy") HttpContext.Current.Session.RemoveAt(i); } catch (Exception) { HttpContext.Current.Session.RemoveAt(i); } i--; } if (!HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.Equals("~/Home/Default")) { HttpContext.Current.Response.Redirect("~/Home/Default"); } throw new System.ComponentModel.DataAnnotations.ValidationException(string.Format("You session has expired or you are currently logged out.", index)); } try { if (HttpContext.Current.Session.Keys.Count > 0 && !HttpContext.Current.Session.Keys.Equals(index)) { return (T)HttpContext.Current.Session[index]; } else { var i = HttpContext.Current.Session.Count - 1; while (i >= 0) { try { var obj = HttpContext.Current.Session[i]; if (obj != null && obj.GetType().ToString() == "Microsoft.Reporting.WebForms.ReportHierarchy") HttpContext.Current.Session.RemoveAt(i); } catch (Exception) { HttpContext.Current.Session.RemoveAt(i); } i--; } if (!HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.Equals("~/Home/Default")) { HttpContext.Current.Response.Redirect("~/Home/Default"); } throw new System.ComponentModel.DataAnnotations.ValidationException(string.Format("You session does not contain {0} or has expired or you are currently logged out.", index)); } } catch (Exception e) { var i = HttpContext.Current.Session.Count - 1; while (i >= 0) { try { var obj = HttpContext.Current.Session[i]; if (obj != null && obj.GetType().ToString() == "Microsoft.Reporting.WebForms.ReportHierarchy") HttpContext.Current.Session.RemoveAt(i); } catch (Exception) { HttpContext.Current.Session.RemoveAt(i); } i--; } if (!HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.Equals("~/Home/Default")) { HttpContext.Current.Response.Redirect("~/Home/Default"); } return default(T); } } public static void Set (string index, T value) { HttpContext.Current.Session[index] = (T)value; } } }
并在您的控制器中设置所有内容,例如登录控制器:
Session Helper.Set("Username", Login User.User Name); Session Helper.Set("Tenant Id", Login User.Tenant Id); SessionHelper.Set("User Type"); SessionHelper.Set("", Login User To String()); SessionHelper.Set("Login User Id", Login User.Login UserId); SessionHelper.Set("Login User", Login User.To String()); SessionHelper.Set ("Tenant", Tenant); SessionHelper.Set ("First name", Login User.First Name); SessionHelper.Set ("Surname", Login User.Surname); SessionHelper.Set ("Vendor ", Vendor ); SessionHelper.Set ("Wholesaler ", Wholesaler ); SessionHelper.Set("Vendor Id", Login User ); SessionHelper.Set("Wholesaler Id", Login User Wholesaler Id);
你只要在任何你想要的地方打电话:
var CreatedBy = SessionHelper.Get("LoginUserId"),
它是一个简单的获取实体或设置为分配它。
public ActionResult DeclareSession() { int id=3; Session["User"]=id; int iUserID =Convert.ToInt32(HttpContext.Current.Session["User"].toString()); return true; }