Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session is null when calling method from one controller to another...MVC

I have an ASP.NET MVC app and i added a new controller to it and call a method from this new controller from an existing controller. I am using session variables and in controller A i call the method in controller B:

if (Session["Grid"] != null){}//session object is fine here
      ControllerB b  = new ControllerB ();
b.CallMethod();

In the new controller, which i'm calling B, the method looks like this:

public object CallMethod(){
    if (Session["Grid"] != null)//session object is null
        {
            //do my thing
        }
  }

The session variable isnt the problem, its the session object. Its completely null, hence my application blows up. The session is alive and well in controller A, so why is it null in controller B? Thank you

like image 955
BoundForGlory Avatar asked Jul 13 '15 16:07

BoundForGlory


People also ask

Why session is null in MVC?

Why is Session null in the constructors of Controllers? It can be accessed from Action methods. Presumably, because the MVC Routing framework is responsible for newing-up a Controller, it just hasn't (re-)instantiated the Session at that point.

How do you make a session null?

You can set session variables in usual way using string as a key e.g. Session["Key"] = obj; To destroy the object in Session set it to null. Session["Key"] = null. you can clear the user session through the session.


1 Answers

That's because ControllerB needs to initializes itself, and as part of this process it also sets Session, Request, Resposne etc accordingly.

So, you need to call the Initialize() method and pass it the current RequestContext. But, since it's marked as protected (because it wasn't meant to be called directly, only using the ControllerFactory), you'll have to expose it:

public class ControllerB : Controller
{
    public void InitializeController(RequestContext context)
    {
        base.Initialize(context);
    }
}

Then in your ControllerA:

var controllerB = new ControllerB();
controllerB.InitializeController(this.Request.RequestContext);

Alternatively, since the Session getter is actually a shorthand for this.ControllerContext.HttpContext.Session (same for Request, Response etc), you can set the ControllerContext instead:

var controllerB = new ControllerB();
controllerB.ControllerContext = new ControllerContext(this.Request.RequestContext, controllerB);

See MSDN

like image 100
haim770 Avatar answered Oct 27 '22 01:10

haim770