In this article we will be discussing how to invoke the action methods base of custom logic and how to redirect a request for an action method to another action method in the same controller or another controller.
We can achieve this with the below two different ways,
- Controller Action Invoker
- Action Invoker
Now let’s discuss them briefly.
Controller Action Invoker
This invokes the specified action by using specific controller context. By implementing ControllerActionInvoker class and overriding InvokeAction action method you can achieve the same. InvokeAction is having controller context and action name as parameter and it returns the result of the executing action.
Let’s see this with the below example.
- Add folder Utilities
- Now add class CustomControllerInvoker as shown below
- public class CustomControllerInvoker:ControllerActionInvoker
- {
- public override bool InvokeAction(ControllerContext controllerContext, string actionName)
- {
- if (actionName.Equals("Index"))
- {
- ViewResult result = new ViewResult();
- result.View = result.ViewEngineCollection.FindView(controllerContext, "About", null).View;
- InvokeActionResult(controllerContext, result);
- return true;
- }
- else
- {
- return base.InvokeAction(controllerContext, actionName);
- }
-
-
- }
- }
Now, above, we have inherited ControllerActionInvoker in CustomControllerInvoker and have overridden InvokeAction. InvokeAction will check if incoming request is for Index action method then it will redirect it to About action method else it will execute called action method.
Now assign CustomControllerInvoker, the invoker of Home controller.
- public HomeController()
- {
- this.ActionInvoker = new CustomControllerInvoker();
-
- }
Action Invoker
This invokes the specified action by using specific controller context. By implementing IActionInvoker interface and overriding InvokeAction action method you can achieve the same. InvokeAction has controller context and action name as parameter and it returns result of executing action.
Let’s see this with the below example,
Now add class CustomActionInvoker in Utilities folder as shown below.
- public class CustomActionInvoker : IActionInvoker
- {
- public bool InvokeAction(ControllerContext controllerContext, string actionName)
- {
- if (actionName.Equals("About", StringComparison.CurrentCultureIgnoreCase))
- {
- controllerContext.HttpContext.Response.Write("This should be the home page");
- return true;
- }
- else
- {
- return false;
- }
- }
- }
Now, above, we have inherited IActionInvoker in CustomActionInvoker and have overridden InvokeAction. InvokeAction will check if incoming request is for About action method then it will show the message “This should be the home page."
Now assign CustomActionInvoker the invoker of Home controller, as shown below.
- public HomeController()
- {
- this.ActionInvoker = new CustomActionInvoker
- }