Monday, July 13, 2009

Custom Action Filter in ASP.Net MVC application

Objective

This article will give an introduction of Action Filter in ASP.Net MVC framework. This will also explain how to create a custom Action filter.

Action Filters in ASP.Net MVC framework

image1.gif

  1. Action filters are attribute
  2. This could be applied on a particular Action
  3. This could be applied on a Controller.
  4. This modifies the way Action executes.
  5. Custom Action filter could also be created and applied.

ASP.Net MVC framework Action filters could be classified as,

image2.gif

How to use an Action filter?

  1. Create a ASP.NET MVC application, by selection File->New->Project->Web
  2. Right click on Controller folder and add one controller. Feel free to give any name. Here name is TestController.
  3. Create an Action inside the controller. Feel free to give any name of the Action. Here name isTestingActionFilter()
  4. TestingActionFilter() action is returning current time as string.
  5. Apply Action filter OutputCache on the Action.
  6. Give required parameter for OutputCache action filter.

    image3.gif

    7. Run the application.
    8. Type http://localhost:1903/Test/TestingActionFilter to get the output. Port number may differ in your case.

    image4.gif

Types of Action filter

image5.gif

image6.gif

Action filter class

  1. The base class of all Action filter are ActionFilterAttribute class.
  2. This is under namespace System.Web.Mvc
  3. It extends FilterAttribute Class.
  4. Class contains four methods , which is shown below

    image7.gif

Creating a Custom Action Filter

image8.gif

  1. Add a class in MVC project. Feel free to give any name.



    image9.gif

  2. Extend the class ActionFilterAttribute
  3. Override the methods. Call method Message in all overridden function.

See full detail: http://www.c-sharpcorner.com/UploadFile/dhananjaycoder/customactionfiltermvc06242009050451AM/customactionfiltermvc.aspx