Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between implementing FilterAttribute, IActionFilter and inheriting from ActionFilterAttribute in asp.net mvc 3?

I see that in one situation we can override OnActionExecuting or OnActionExecuted methods inheriting from ActionFilterAttribute class like this:

public class MyFilterAttribute : ActionFilterAttribute {     public override void OnActionExecuted(ActionExecutedContext filterContext)     { // bla bla } } 

And in other situation we also can implement IActionFilter and FilterAttribute like this:

public class MySecondFilterAttribute : FilterAttribute, IActionFilter  {      public void OnActionExecuted(ActionExecutingContext filterContext) {} } 

So, is there any differences between these two approaches, maybe any particular situations where it would be preferable to use one of them over the other??

Thanks in advance.

like image 389
Aleksei Chepovoi Avatar asked Feb 14 '13 16:02

Aleksei Chepovoi


People also ask

What is difference between OnActionExecuting and OnActionExecuted in MVC?

OnActionExecuting – This method is called before a controller action is executed. OnActionExecuted – This method is called after a controller action is executed. OnResultExecuting – This method is called before a controller action result is executed.

How action filters are implemented in MVC?

ASP.NET MVC provides Action Filters for executing filtering logic either before or after an action method is called. Action Filters are custom attributes that provide declarative means to add pre-action and post-action behavior to the controller's action methods.

Which filter will be execute at first using ASP.NET MVC?

as you can see from the below diagram, as soon as the controller starts execution through Action Invoker, Authentication and authorization filters are the very first filters to be triggered, followed by model binding which maps request and route data to action parameters.


1 Answers

Basically FilterAttribute provides the most low level behaviour of MVC Attributes and implements the IMvcFilter that provides the Order and AllowMultiple properties.

ActionFilterAttribute is the basis for filtering actions and results, since is a implementation of IActionFilter, IResultFilter and inherit from FilterAttribute.

Your MySecondFilterAttribute implementation leads to ActionFilterAttribute without IResultFilter capabilities (OnResultExecuting and OnResultExecuted).

like image 85
wnascimento Avatar answered Oct 16 '22 17:10

wnascimento