Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ControllerContext is null

I have this MVC4 controller (ControllerB):

public class MyControllerB : Controller
{
    public bool Check(string actionName, ControllerBase controllerBase)
    {
        ControllerContext controllerContext = new ControllerContext(this.ControllerContext.RequestContext, controllerBase);

        ...
    }
}

I'm calling ControllerB's Check method from "ControllerA", like so:

bool b = new MyControllerB().Check("Index", this);

I get Object reference not set to an instance of an object because this.ControllerContext is null.

If I move the Check method to ControllerA, it works just fine. But I need this method to be in a different controller. How can I fix my code so that ``this.ControllerContext` will not be null?

like image 202
Administrateur Avatar asked May 26 '26 21:05

Administrateur


1 Answers

The ControllerContext is null because you are manually creating the ControllerB instance from ControllerA.

Normally, IController instances are created by the registered IControllerFactory, typically System.Web.Mvc.DefaultControllerFactory. The controller factory will new() the instance and initialize settings properly.

As @DZL says, it is normally much better to have both controllers subclass a BaseController class, which can have shared initialization and shared properties and methods.

I don't understand the business logic of what you are trying to do, but here's a code example of using the base class from the 2 controllers:

namespace MyNamespace.Controllers
{
    public class MyControllerBase : Controller
    {
        public bool Check(string actionName, ControllerBase controllerBase)
        {
            ControllerContext controllerContext = new ControllerContext(this.ControllerContext.RequestContext, controllerBase);
            return false;
        }
    }
    public class MyControllerA : MyControllerBase
    {
        ActionResult Index()
        {
            bool b = base.Check("Index", this);
            return View();
        }
    }
    public class MyControllerB : MyControllerBase
    {
        ActionResult Index()
        {
            bool b = base.Check("Index", this);
            return View();
        }
    }
}

If you really want to do exactly what you are asking, you'll have to call IControllerFactory.CreateController(requestContext, controllerName) instead of new ControllerB(), but that is a really convoluted way of doing things - I wouldn't recommend it.

like image 189
Raul Nohea Goodness Avatar answered May 28 '26 11:05

Raul Nohea Goodness



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!