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

StackOverflow https://stackoverflow.com/questions/23629089

Domanda

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.**
      }

    }
È stato utile?

Soluzione

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;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top