Rahul
Rahul

Reputation: 2307

How to use Session Variable in MVC

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

Upvotes: 15

Views: 87243

Answers (5)

Shravan Ravva
Shravan Ravva

Reputation: 41

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

Upvotes: -1

Quintin moodley
Quintin moodley

Reputation: 51

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 e.g. 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.

Upvotes: 0

Phill
Phill

Reputation: 18796

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.

Upvotes: 27

Hozefa Laxmidhar
Hozefa Laxmidhar

Reputation: 102

In controller, you can access like this..

YourControllerID.ControllerContext.HttpContext.Session["_SessionCompany"]

Upvotes: 1

Spikeh
Spikeh

Reputation: 3695

You should not set session variables in Application_Start(), as that method is only called once, when the application kicks off in IIS. It is not session based.

In addition, I assume your controller has a Session property? Have you set it correctly?

Use HttpContext.Current.Session["_SessionCompany"] rather than this.Session["_SessionCompany"] - that should work.

Upvotes: 4

Related Questions