ASP.NET MVC initializes the controller and invokes actions programmatically

I create a controller of scheduled tasks - these tasks will call the Controller and Action , fixing the result. I would prefer it all to happen on the backend and not include http calls.

This is similar to what happens with unit testing - for example:

var controller = new TestController(); var result = controller.Index("TestParameter") as ViewResult; 

The problem in this example: the controller and the action are not dynamic, does anyone know how to initialize the controller and call the action with the controller name and action as a string parameter? For example:

 public ActionResult run(string controllerName, string actionName) { var controller = new Controller(controllerName); var result = controller.action(actionName).("TestParameter") as ViewResult; return Content(result); } 
+7
c # asp.net-mvc asp.net-mvc-4
source share
2 answers

Use ControllerFactory together with ActionDescriptor to dynamically execute an 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

+13
source share

I'm not sure where your real problem is, do you want to test the controller / action or want to test the functionality of your tasks?

  • If you need to test the controller / action , it will include the HttpContext .
  • If you need to test your functionality, it’s better to separate it at the service / repository level, and you can test using the repository template.
-3
source share

All Articles