Reputation: 53
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);
}
Upvotes: 9
Views: 6964
Reputation: 417
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
.Upvotes: -3
Reputation: 49095
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
Upvotes: 15