for which purpose we need to use MVC Actionfilters like OnActionExecuting and OnActionExecuted?

478 views Asked by At

I know that how to use Actionfiltes in MVC but i am not understand that why we are using it, because we can write logic in action for both of this before execution and after then what is purpose of it? if any one give me proper example and explanation then it would be helpful me.

Regards, Vinit Patel

2

There are 2 answers

0
Zoltán Tamási On

Action filters give you a centralized way to define a logic to execute before or after actions are executed. A few examples could be

  • common exception handling
  • authorization
  • logging

You can add action filters to each action separately, or you can add them globally to all action using Global filters.

In general a filter means a piece of unit which you can chain into some kind of process to intercept and sometimes modify the flow. In terms of for example audio technology, a filter can be an effect (equalizer, compressor, etc.). In terms of MVC, it can be a unit which you want to plug into the MVC processing flow.

0
Abhishek Duppati On

Action filters are amazing as it enables you to catch the actions request, requested and the result's executing and executed techniques to play out some custom preparing that your application needs. This can be exceptionally helpful on the off chance that you would prefer not to modify some bit of code for each activity or controller and that is a decent method to run your very own action filter.

Types of Available Action Filters in MVC:

Authorize: AuthorizeAttribute class is used to specify the access to a controller or action method which is limited to users who meet the approval necessity.

HandleError: HandleErrorAttribute class is used to handle an exception that is thrown by an action method.

ValidateAntiForgeryToken: ValidateAntiForgeryTokenAttribute class is used to prevent cross-site request forgeries.

ValidateInput: ValidateInputAttribute class is used to mark action methods whose input must be validated.

OutputCache: OutputCache Attribute class is used to mark an action method or controller whose output is cached.