在MVC 6 alpha4中手动实例化控制器 [英] Manually instantiate a Controller in MVC 6 alpha4
问题描述
我正在对MVC 6 alpha 4进行一些实验.尝试手动激活控制器并返回它而不是HomeController,但这是行不通的.请帮忙.
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;
}
}
我已经调试了代码. MyController
的构造函数被调用,并且MyController
从CreateController
方法返回,但出现错误.调试器永远不会到达IActionResult Index()
.这是我得到的错误.
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()
推荐答案
以下是答案.
首先,MyController
需要从HomeController
继承.
其次,在激活控制器之前,我需要在RouteData中更改"controller"值.
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";
这篇关于在MVC 6 alpha4中手动实例化控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!