Problem with Ninject and MVC3 Dependency injection action filter on Controller and Action

天涯浪子 提交于 2019-12-04 14:21:52

This happens if your controller and one of its actions have the LogActionAttribute at the same time.

(I know the answer's already accepted but this is for the sake of documentation.)

In case you can only use the release version, a temporary solution is to create two subclasses and register them separately. Here's an example from my application:

public class MyAuthorizationFilter : IAuthorizationFilter
{
   /* call base ctor */
}

public class MyControllerAuthorizationFilter : MyAuthorizationFilter
{
   /* call base ctor */
}

public class MyActionAuthorizationFilter : MyAuthorizationFilter
{
}

Then setup filter bindings:

this.BindFilter<MyControllerAuthorizationFilter>(FilterScope.Controller, 0)
            .WhenControllerHas<MyAttribute>()
            .WithConstructorArgumentFromControllerAttribute<ProtectedAttribute>(/*...*/) ;

this.BindFilter<MyActionAuthorizationFilter>(FilterScope.Action, 0)
            .WhenActionMethodHas<MyAttribute>()
            .WithConstructorArgumentFromActionAttribute<ProtectedAttribute>(/*...*/) ;

Make sure to call the correct 'WithConstructorArgumentFrom[Controller/Action]Attribute method or you'll get a 'Sequence has no elements' error (I did).

Better workaround. In fact I use this in the new version too rather than have two bindings for controllers and actions.

this.BindFilter<MyFilter>(FilterScope.Global, int.MinValue)
    .When((controllerContext, actionDescriptor) =>
                                                 controllerContext
                                                .Controller
                                                .GetType()
                                                .GetCustomAttributes(typeof(MyAttribute),true)
                                                .Length > 0 
    || actionDescriptor.GetCustomAttributes(typeof(MyAttribute), true).Length > 0);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!