简体   繁体   中英

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. I would rather have all this happen on the backend and not involve http calls.

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:

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

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 .
  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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