Assigning a value to a session by giving a reference to an object not set for an object exception instance in MVC

Problem:

I am trying to assign a value to a session object in MVC Controller, it provides an exception as the Object reference is not installed in the object instance.

I have two controllers

  • Maincontroller
  • SecondaryController

When I assign a value to a session in the Main controller, it works fine.but, if I assign the same value to the Test () method in the secondary controller, it gives an error.

What am I 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.** } } 
+7
c # asp.net-mvc session controller
source share
1 answer

This is because the session variable is only available in the Standard ASP.NET MVC Controller (master controller). To access session variables in the secondary controller, you must use

 System.Web.HttpContext.Current.Session["LogID"] = 10; 
+10
source share

All Articles