简体   繁体   English

ASP.NET MVC以编程方式初始化Controller并调用操作

[英]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: 使用ControllerFactoryActionDescriptor动态执行操作:

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;
}

See MSDN 请参阅MSDN

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? 我不确定你真正的问题在哪里 - 你想测试控制器/动作还是你想测试你的工作功能?

  1. If you need to test controller/action it would involve HttpContext . 如果你需要测试控制器/动作 ,它将涉及HttpContext
  2. If you need to test your job functionality better way to separate that in your service / repository layer and you can do testing with using repository pattern. 如果您需要更好地测试作业功能,可以在服务/存储库层中将其分开,并且可以使用存储库模式进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM