无法启动动作过滤器

时间:2013-10-04 20:12:41

标签: asp.net-mvc ninject

简化了代码示例以专注于重要位。

我有三个MVC应用程序,其中一个运行在https://localhost/App/,另外两个运行在它下面(https://localhost/App/App1/https://localhost/App/App2/)。到目前为止,我一直在授权用户使用从ActionFilterAttribute派生的属性,并且它的工作非常精彩。 working属性如下所示:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class EntitleAttribute : ActionFilterAttribute
{
    public string PermissionName { get; private set; }

    public EntitleAttribute(string permissionName = null)
    {
        PermissionName = permissionName;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        bool hasPermission = IsAccessibleInCurrentContext();
        if (!hasPermission)
        {
            // If the user does not have rights on this action, return a 401.
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}

但是,我最近转换为使用Ninject,我正在尝试将其转换为Action + Filter设置,以便我可以注入过滤器。所以现在,为了声明用户需要访问操作的授权,我有一个如下设置的属性:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class EntitleAttribute : Attribute
{
    public string PermissionName { get; private set; }

    public EntitleAttribute(string permissionName = null)
    {
        PermissionName = permissionName;
    }
}

我有一个像这样的过滤器:

public class EntitleFilter : IActionFilter
{
    private readonly string _permissionName;

    public EntitleFilter(string permissionName)
    {
        _permissionName = permissionName;
    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        bool hasPermission = IsAccessibleInCurrentContext();
        if (!hasPermission)
        {
            // If the user does not have rights on this action, return a 401.
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // Nothing.
    }
}

我在NinjectModule中设置依赖注入,如下所示:

// Bind authorization handling.
this.BindFilter<EntitleFilter>(FilterScope.Controller, 0)
    .WhenControllerHas<EntitleAttribute>()
    .WithConstructorArgumentFromControllerAttribute<EntitleAttribute>("permissionName", attr => attr.PermissionName);
this.BindFilter<EntitleFilter>(FilterScope.Action, 0)
    .WhenActionMethodHas<EntitleAttribute>()
    .WithConstructorArgumentFromActionAttribute<EntitleAttribute>("permissionName", attr => attr.PermissionName);

当我正在运行App时,一切都运行良好 - OnActionExecuting方法会在每次通话时被点击。但是,即使在App1之后,也永远不会在App2iisreset中调用该方法。在AppApp1的首次运行中,过滤器设置似乎没有受到影响,这似乎很奇怪。

每个应用程序的设置都相同,都使用通用类。每个应用中的HomeController在控制器上都有EntitleAttribute,而不是Index操作,因此它们一致。

我也尝试过使用AuthorizationAttribute和IAuthorizationFilter,结果相同。任何方向都将不胜感激。

0 个答案:

没有答案