Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behaviour with asp.net mvc action filters AttributeUsage

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?

like image 414
Ben Foster Avatar asked Jul 18 '11 11:07

Ben Foster


People also ask

What is the need of action filters in ASP.NET 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.

Can we override filters in MVC?

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.

What are the different types of MVC action filter does ASP.NET MVC 3.0 life cycle has?

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.


1 Answers

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.

like image 65
Bradley Grainger Avatar answered Oct 14 '22 21:10

Bradley Grainger