Handle Unknown Action Sample in MVC: Day 41

Consider a scenario where we call an action method using an action name that is not available in the controller. We call the correct controller but the action name that we pass is not in the controller. So in this situation we need to handle the exception. For that there is a method called "HandleUnknownAction". HandleUnknownAction is a virtual method available inside the controller abstract class. It is called when a request matches the controller but no method with the specified action name is found in the controller.

Let's see the step-by-step implementation:

  1. Create an MVC project from the "Empty" template.

    Right-click on "Controllers" and select "Add" >> "Controller...".

  2. Select "MVC 5 Controller - Empty" to add an empty controller.

    Click on the "Add" button.

  3. Name the controller "HomeController".

    The Index() action result method will be added.

  4. To add a view, right-click on "Download" and select "Add View...".

  5. Name the view and select "Empty (without model)" as the template. Click on the "Add" button.

    Add the title inside the index page as in the following:

    index page

  6. Now run the project and you can see that the index page is rendered with title.

    Local host

  7. Now let's change the action name in the address bar, in other words from index to index1 and try to reload the page.

    application error

    It throws a server error since it is not handled in the application. To handle this kind of situation or error, we need to override the virtual method called "HandleUnKnownAction".

  8. Inside HomeController, we override the "HandleUnknownAction" method. So whenever an action that is not there in the controller is requested then this method is called. Once it is called we can handle this scenario however we want. In this example we redirect it to the "Index" action method. For this we use the RedirectToAction method to redirect to the specified action using action name.

    ExecuteResult enables the processing of the result of an action method by a custom type that inherits from the action result class. ControllerContext is the contex within which the result is executed.

    cs code

  9. Now run the project and change the action name from index to index1 in the address bar and try to debug. It jumps to the HandleUnknownAction method and finally redirects to the index action method and renders the index view.


<<File Download Sample in MVC: Day 40

Similar Articles