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;
Author by
Vishal I P
Updated on June 28, 2022Comments
-
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
- MainController
- 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 almost 10 yearsThanks for your suggestion.
-
HelpASisterOut almost 10 yearsHello. 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 about 7 yearsi'M HAVING THE SAME PROBLEM!!
-
AlexGH almost 7 yearssame thing was happening with me, I was using a controller inside Areas folder, thank you!
-
Lester over 5 yearsi am having the same problem, and this solution is working for me