[英]ASP.NET MVC initialize Controller and call action programatically
I am building a scheduled jobs controller - these jobs will call a Controller and an Action capturing the result. 我正在构建一个预定的作业控制器 - 这些作业将调用一个Controller和一个捕获结果的Action 。 I would rather have all this happen on the backend and not involve http calls. 我宁愿在后端发生所有这些,也不要涉及http调用。
Its kind of like what happens with Unit testing - for instance: 它有点类似于单元测试 - 例如:
var controller = new TestController();
var result = controller.Index("TestParameter") as ViewResult;
The issue is in this example the controller and action are not dynamic, does anyone know how to initialize a controller and call an action with the name of the controller and action as string paramater? 问题在于此示例中控制器和操作不是动态的,是否有人知道如何初始化控制器并使用控制器名称和操作作为字符串参数调用操作? Such as - 如 -
public ActionResult run(string controllerName, string actionName)
{
var controller = new Controller(controllerName);
var result = controller.action(actionName).("TestParameter") as ViewResult;
return Content(result);
}
Use the ControllerFactory
along with the ActionDescriptor
to dynamically execute the action: 使用ControllerFactory
和ActionDescriptor
动态执行操作:
public ActionResult Run(string controllerName, string actionName)
{
// get the controller
var ctrlFactory = ControllerBuilder.Current.GetControllerFactory();
var ctrl = ctrlFactory.CreateController(this.Request.RequestContext, controllerName) as Controller;
var ctrlContext = new ControllerContext(this.Request.RequestContext, ctrl);
var ctrlDesc = new ReflectedControllerDescriptor(ctrl.GetType());
// get the action
var actionDesc = ctrlDesc.FindAction(ctrlContext, actionName);
// execute
var result = actionDesc.Execute(ctrlContext, new Dictionary<string, object>
{
{ "parameterName", "TestParameter" }
}) as ActionResult;
// return the other action result as the current action result
return result;
}
I am not sure where is your real problem lies—do you want to test controller/action or do you want to test functionality of your jobs? 我不确定你真正的问题在哪里 - 你想测试控制器/动作还是你想测试你的工作功能?
HttpContext
. 如果你需要测试控制器/动作 ,它将涉及HttpContext
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.