Assigning value to session, giving object reference not set to an instance of an object exception in MVC

14,564

This is because Session variable is only available in Standard ASP.NET MVC Controller (main controller). In order to access session variables in secondary controller you should use

System.Web.HttpContext.Current.Session["LogID"] = 10;
Share:
14,564
Vishal I P
Author by

Vishal I P

Updated on June 28, 2022

Comments

  • Vishal I P
    Vishal I P almost 2 years

    Problem Statement:

    I'm trying to assign a value to session object in MVC Controller it is giving exception as Object reference not set to an instance of an object.

    I'm having two controllers

    1. MainController
    2. SecondaryController

    When I assign value to session in Main controller it is working fine.but if i assign same value in a Test() method in secondary controller,it is giving error.

    What i'm doing wrong here???

    Main Controller :

     public class MainController: Controller
         {
            SecondaryController secCont=new SecondaryController();
            public ActionResult Index(LoginModel loginModel)
              {
    
                if (ModelState.IsValid)
                    {
                     Session["LogID"] = 10;
                      //This is working fine.
                      //Instead of this i want call secCont.Test(); method where value for session assigned, it is giving error.
    
                    }
                  return View(loginModel);
    
               }
         }
    

    Secondary Controller :

     public class SecondaryController: Controller
       {
         public void Test()
         {
            Session["LogID"] = 10;
            // Giving Error as **Object reference not set to an instance of an object.**
          }
    
        }
    
  • Vishal I P
    Vishal I P almost 10 years
    Thanks for your suggestion.
  • HelpASisterOut
    HelpASisterOut almost 10 years
    Hello. I am having the same problem. I tried referencing System.Web but it still gave me the error That Object reference not set to an instance of an object. Please advise.
  • Tania Marinova
    Tania Marinova about 7 years
    i'M HAVING THE SAME PROBLEM!!
  • AlexGH
    AlexGH almost 7 years
    same thing was happening with me, I was using a controller inside Areas folder, thank you!
  • Lester
    Lester over 5 years
    i am having the same problem, and this solution is working for me