What are Filters in ASP.NET MVC?


ASP.NET MVC 5 is a web framework based on Model-View-Controller (MVC) architecture.
Developers can build dynamic web applications using the ASP.NET MVC framework
that enables a clean separation of concerns, fast development, and TDD friendly.

ASP.NET MVC Filter is a custom class where you can write custom logic to execute before or after an action method executes.
Filters can be applied to an action method or controller in a declarative or programmatic way.
Declarative means by applying a filter attribute to an action method or controller class and
programmatic means by implementing a corresponding interface.

ASP.NET MVC
  1. MVC Filters are used to execute custom logic before or after executing the action method.
  2. MVC Filter types:
    *Authentication filters - Confirm that you are a valid or invalid user.
    *Action filters - this filter can apply to a controller action or an entire controller before and after executing.
    *Result filters - These filters contain logic that is executed before and after a view result is executed.
    *Exception filters - these filters can be used as a handling error raised by controller actions or actions results. *Authorization filter - Authorization filters implement authentication and authorization for controller actions.
  3. Filters can be applied globally in FilterConfig class, at controller level or action method level.
  4. Custom filter class can be created by implementing FilterAttribute class and corresponding interface.

Action filter executes before and after an action method executes.

Action filter attributes can be applied to an individual action method or to a controller.

When an action filter applied to the controller then it will be applied to all the action methods in that controller.

  1. Action filters allow pre and post-processing logic to be applied to an action method.
  2. Action filters are generally used to apply cross-cutting concerns such as logging, caching, authorization etc.
  3. Action filter can be registered as other filters at the global, controller or action method level.
  4. Custom action filter attribute can be created by deriving ActionFilterAttribute class or
    implementing IActionFilter interface and FilterAttribute abstract class.
  5. Every action filter must override OnActionExecuted, OnActionExecuting, OnResultExecuted, OnResultExecuting methods.

This was an introductory article for beginner's to make then learn the concept of filters and attributes in the ASP.NET MVC application. I hope this has been a little informative. 


If you found this article useful, share it.*

 SoftCodeLearner: ASP.NET Interview questions and answers

SoftCodeLearner: ASP.NET MVC - Model View Controller

Umesh Mahajan | Facebook

No comments:

Post a Comment