Manually instantiate a Controller in MVC 6 alpha4

人盡茶涼 提交于 2019-12-25 00:04:59

问题


I am doing some experimentation with MVC 6 alpha 4. Trying to activate a controller manually and returning it instead of HomeController but this doesn't work. Any help please..

So far I have created my own controller factory with this code.

 public class MyControllerFactory : IControllerFactory
{
    public object CreateController(ActionContext actionContext)
    {
    var actionDescriptor = actionContext.ActionDescriptor as Microsoft.AspNet.Mvc.ReflectedActionDescriptor;

    Type controllerType = Type.GetType("Hello.Controllers.MyController");
    var controller = _typeActivator.CreateInstance(_serviceProvider, controllerType);

    actionContext.Controller = controller;
    _controllerActivator.Activate(controller, actionContext);

    return controller;
    }
}

I have debugged the code. The constructor of MyController gets called and MyController is being returned from the CreateController method but I get the error. The debugger never reaches to IActionResult Index(). Here is the error that I get.

System.Reflection.TargetException: Object does not match target type.
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr,      Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder,     Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at Microsoft.AspNet.Mvc.ReflectedActionExecutor.<ExecuteAsync>d__2.MoveNext()

回答1:


Here is the answer.

Firstly, MyController needs to inherit from HomeController.
Secondly, I need to change the 'controller' value in RouteData before activating the controller.

actionContext.RouteData.Values["controller"] = "My";


来源:https://stackoverflow.com/questions/26325854/manually-instantiate-a-controller-in-mvc-6-alpha4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!