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
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With