如何在MVC中使用会话变量

时间:2013-12-03 11:48:10

标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 session

我在" 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();
        }

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

我得到的是例外情况 "Object Reference not set to an Insatance of an object" 在行中的Global.asax Application_Start

HttpContext.Current.Session.Add("_SessionCompany",temp);

5 个答案:

答案 0 :(得分:21)

启动Application的线程不是用户向网页发出请求时使用的请求线程。

这意味着当您在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);
}

这可以解决您的问题。

答案 1 :(得分:4)

您不应该在Application_Start()中设置会话变量,因为当应用程序在IIS中启动时,该方法仅被调用一次。它不是基于会话的。

另外,我假设你的控制器有一个Session属性?你准确设置了吗?

使用HttpContext.Current.Session["_SessionCompany"]而不是this.Session["_SessionCompany"] - 这应该有用。

答案 2 :(得分:1)

在控制器中,您可以像这样访问..

YourControllerID.ControllerContext.HttpContext.Session [ “_ SessionCompany”]

答案 3 :(得分:0)

使用此助手类:

namespace Projectname.UI.HtmlHelpers
{
    //[DebuggerNonUserCodeAttribute()]
    public static class SessionHelper
    {
        public static T Get<T>(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<T>(string index, T value)
        {
            HttpContext.Current.Session[index] = (T)value;
        }
    }
}

并在您的控制器中设置所有内容,例如登录控制器:

Session Helper.Set<string>("Username", Login User.User Name);
Session Helper.Set<int?>("Tenant Id", Login User.Tenant Id);
SessionHelper.Set<User Type>("User Type");
SessionHelper.Set<string>("", Login User To String());
SessionHelper.Set<int>("Login User Id", Login User.Login UserId);
SessionHelper.Set<string>("Login User", Login User.To String());
SessionHelper.Set<string>("Tenant", Tenant);
SessionHelper.Set<string>("First name", Login User.First Name);
SessionHelper.Set<string>("Surname", Login User.Surname);
SessionHelper.Set<string>("Vendor ", Vendor );
SessionHelper.Set<string>("Wholesaler ", Wholesaler );
SessionHelper.Set<int?>("Vendor Id", Login User );
SessionHelper.Set<int?>("Wholesaler Id", Login User Wholesaler Id);

您只需在任意位置调用它:

var CreatedBy = SessionHelper.Get<int>("LoginUserId"),

这是一个简单的获取实体或设置为分配它。

答案 4 :(得分:-1)

public ActionResult DeclareSession()
{ 
    int id=3;
    Session["User"]=id;
    int iUserID =Convert.ToInt32(HttpContext.Current.Session["User"].toString());
    return true;
}