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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With