I have an action filter with the following signature
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class UnitOfWorkAttribute : ActionFilterAttribute
According to MSDN:
The AllowMultiple property indicates whether multiple instances of your attribute can exist on an element. If set to true, multiple instances are allowed; if set to false (the default), only one instance is allowed.
In MVC the behaviour seems a bit strange. When I decorated an action with this attribute, I found that the OnActionExecuting
method of the filter was executed twice.
The filter was only declared on the action, not on the controller, and I had cleared any global filters. Could someone explain this behaviour?
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.
ASP.NET MVC 5 has a new feature called Filter Overrides, which allows you to clear or replace certain filter types created in higher scopes. For example, if you created a global action filter or controller action filter, you could override those filters on a case-by-case basis at the controller action level.
Types of Action Filters in MVC The ASP.NET MVC framework maintains various filters: Authorisation filters: Executes the IAuthorisationFilter attribute. Action filters: Performs the IActionFilter attribute. Result filters: Execute the IResultFilter attribute.
I encountered the same problem. (I installed a global filter (just once) and discovered that its IActionFilter
and IResultFilter
methods were being called twice for each request. The filterContext.HttpContext
object being passed to these methods was exactly the same for both calls.)
This turned out to be due to using Html.Action
in the view. It appears (from looking at the call stack) that calling Html.Action
reentrantly processes the child action method (during the processing of the initial action method) and the filters get invoked for both.
You can detect this situation by checking the filterContext.IsChildAction
property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With