Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 824
Harleyz Avatar asked Mar 10 '15 15:03

Harleyz


1 Answers

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

like image 129
haim770 Avatar answered Oct 12 '22 11:10

haim770