简体   繁体   English

如何在MVC中使用会话变量

[英]How to use Session Variable in MVC

I have declared Session variable in "Global.asax" file as, 我在“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);
        }

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. 请帮我解决这个问题,如何将会话变量访问到我的控制器的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 我在Global.asax中的Application_Start中获得了一个异常,例如"Object Reference not set to an Insatance of an object"

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. 启动Application的线程不是用户向Web页面发出请求时使用的请求线程。

That means when you set in the Application_Start , you're not setting it for any user. 这意味着当您在Application_Start设置时,您不会为任何用户设置它。

You want to set the session on Session_Start event. 您想要在Session_Start事件上设置会话。

Edit: 编辑:

Add a new event to your global.asax.cs file called Session_Start and remove the session related stuff from Application_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);
}

This should fix your issue. 这应该可以解决您的问题。

You should not set session variables in Application_Start(), as that method is only called once, when the application kicks off in IIS. 您不应该在Application_Start()中设置会话变量,因为当应用程序在IIS中启动时,该方法仅被调用一次。 It is not session based. 它不是基于会话的。

In addition, I assume your controller has a Session property? 另外,我假设你的控制器有一个Session属性? Have you set it correctly? 你准确设置好了吗?

Use HttpContext.Current.Session["_SessionCompany"] rather than this.Session["_SessionCompany"] - that should work. 使用HttpContext.Current.Session["_SessionCompany"]而不是this.Session["_SessionCompany"] - 这应该有效。

In controller, you can access like this.. 在控制器中,您可以像这样访问..

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

Use this helper class: 使用这个助手类:

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;
        }
    }
}

and in your controller you set everything eg a login controller: 并在您的控制器中设置所有内容,例如登录控制器:

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);

and you just call it anywhere you want: 你可以在任何地方调用它:

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

it is a simple get to the the entity or set to assign it. 它是一个简单的获取实体或设置为分配它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM