Free Web Development Online Tutorials, Learn to Code
Learn Asp.net MVC C#, Asp.net MVC Tutorial for Beginners, Model View Controller

Filters in Asp.net MVC Example

What is Filters in Asp.net MVC?

In general terms filters are some mechanism that helps to verify any action, in Asp.net MVC there are some such filters, filters are basically custom classes that provide a way to check pre-action and post-action behavior of any action methods in controller

Type of Filters in Asp.net MVC

In ASP.NET MVC framework there are four different types of filters:
  • Authorization Filters − Implements the IAuthorizationFilter attribute.
  • Action Filters − Implements the IActionFilter attribute.
  • Result Filters − Implements the IResultFilter attribute.
  • Exception Filters − Implements the IExceptionFilter attribute.

Filters are executed before or after any action, we simply can apply filters on any controller or on any action.

For example, Authorize filters can be applied on any action where you want to make sure that the request has come from an authorized person or HandleError filter can be applied on any action or any controller.

Let's look at some example

Many Action Filters in Asp.net MVC

  • HandleError − Handles errors raised when a controller action is executed.
    public class mvcController : Controller 
    { 
        [HandleError] 
        public ActionResult filters() 
        { 
        return View();
        } 
    }
  • Authorize − Enables you to restrict access to a particular user or role.
    public class mvcController : Controller
    {
        [Authorize]
        public ActionResult filters()
        {
            return View();
        }
    }

  • OutputCache − Caches the output of a controller action for a specified amount of time.
    public class mvcController : Controller
    {
        [OutputCache(Duration = 50)]
        public ActionResult filters() 
        { 
            return View(); 
        } 
    }

In all above example we have applied filter on Action, same way you also can apply filter on any controller.

You also can create your own customize filter class inherited from ActionFilterAttribute or any other class which is finally inherited from FilterAttribute class.

implementation may look like
internal class MyCustomFilter : ActionFilterAttribute 
{             
    public override void OnActionExecuted(ActionExecutedContext filterContext) 
    {
        var response = filterContext.HttpContext.Response; 
               
        // do whatever you want to do with request object 
    } 
}

Once your custom filter is ready, same way you can apply on any action or any controller in your application
You may look at how a custom compress filter can be written


Comment
Name
Email
Website
Subscribe