ASP.NET MVC > Action Invoker

Action Invoker in ASP.NET MVC

How to create custom action invoker in ASP.NET MVC?


In the previous post, we learnt how to create controller action invoker using ControllerActionInvoker. In this post we shall learn how to create custom action invoker in ASP.NET using IActionInvoker interface that is part of ASP.NET MVC framework.

To understand this, create a class and inherit it with IActionInvoker interface. By inheriting this,  we will be forced to implement the InvokeAction method. In this method, we can write our own behavior of a particular action request.

In the InvokeAction method, we have checked for the actionName and if it is Index then we are writing a custom text "This should be the home page" to the output and the same gets displayed to the end user. If the actionName is not "index" then we simply returns false that displays the default view assigned for this action method in the controller.

    public class CustomActionInvoker : IActionInvoker
    {
        public bool InvokeAction(ControllerContext controllerContext, string actionName)
        {
            if (actionName.Equals("Index", StringComparison.CurrentCultureIgnoreCase))
            {
                controllerContext.HttpContext.Response.Write("This should be the home page");
                return true;
            }
            else
            {
                // controllerContext.HttpContext.Response.Redirect("/");
                return false;
            }
        }
    }

As in case of ControllerActionInvoker, we will have to set the instance of the above class to the ActionInovker inside the controller constructor.

 public class ActionInvokerController : Controller
    {

        public ActionInvokerController()
        {
            this.ActionInvoker = new CustomActionInvoker();
        }

        public ActionResult Index()
        {
            return View();
        }
}

Now if we make following request

  • /ActionInvoker/Index -  we will see simply seeing plain text "This should be the home page" output to the browser window
  • For other action method request, we will see the default view assigned into the action method of the controller.

Read how to create controller dependency injection in ASP.NET MVC here.

 Views: 1977 | Post Order: 140



Write for us