Session is null when calling method from one controller to another...MVC
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