开发者

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 ac开发者_如何学编程tion, not on the controller, and I had cleared any global filters. Could someone explain this behaviour?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜