ControllerContext is null

后端 未结 1 1867
生来不讨喜
生来不讨喜 2021-01-06 18:56

I have this MVC4 controller (ControllerB):

public class MyControllerB : Controller
{
    public bool Check(string actionName, ControllerBase con         


        
相关标签:
1条回答
  • 2021-01-06 19:45

    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.

    0 讨论(0)
提交回复
热议问题