15

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);
5
  • What error are you getting? Commented Dec 3, 2013 at 11:50
  • 3
    @GeorgeStocker he specified it in ApplicationStart, it doesn't matter what the exception is, his code wont work, no doubt its a NullReferenceException though. Commented Dec 3, 2013 at 11:52
  • You should probably use the Session_Start event Commented Dec 3, 2013 at 11:56
  • 2
    @Phil The error isn't for us; it's for the future users that make this mistake and searching (rightfully so) for "Error text + Session Variable". Commented Dec 3, 2013 at 11:58
  • ok @GeorgeStocker - fair point! Commented Dec 3, 2013 at 12:00

5 Answers 5

27

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

3 Comments

But I am getting Exception in Application_Start if Global.asax
Yes, you will get an exception if you try to access HttpContext.Current.Session in the Application_Start() method, as the code is ran in a different thread within IIS - it is executed by the application pool, independently of any users connecting to your website. At this moment, a Session does not exist. As @Phill has said, you should use the Session_start() method in Global.asax instead.
The Session property is a property that comes from the Controller abstract class.
1

In controller, you can access like this..

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

Comments

0

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.

1 Comment

If this answers the OP's question you should explain how. Just dropping a blob of code down does nothing to help the OP understand their problem, or your solution.
-1
public ActionResult DeclareSession()
{ 
    int id=3;
    Session["User"]=id;
    int iUserID =Convert.ToInt32(HttpContext.Current.Session["User"].toString());
    return true;
}

1 Comment

using the old Session variable way on mvc will sometimes freak out and then you have to create a cookiesession manager.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.