Ben Foster
Ben Foster

Reputation: 34800

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?

Upvotes: 14

Views: 4544

Answers (2)

LordHits
LordHits

Reputation: 5083

I've had the OnActionExecuting method from my custom action filter class executing twice too.

At some point I added this to my Application_Start method in the global.asax.cs file:

GlobalConfiguration.Configuration.Filters.Add(new MyCustomActionFilter());

Apparently, my action filter was already added to the Filters collection which was leading to the double call to OnActionExecuting and OnActionExecuted. So that line in the applicaton_start was not needed.

Upvotes: 0

Bradley Grainger
Bradley Grainger

Reputation: 28162

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.

Upvotes: 33

Related Questions