ASP.NET MVC 5中的Actionfilter注入

Afl*_*red 4 asp.net asp.net-mvc dependency-injection ninject inversion-of-control

我有一个简单的过滤器.

public class IsAdmin : ActionFilterAttribute, IAuthenticationFilter
{
    private string _roleName;
    IBusinessIdentity _identity;

    public IsAdmin(string roleName, IBusinessIdentity identity)
    {
        this._roleName = roleName;
        this._identity = identity;
    }

    public void OnAuthentication(AuthenticationContext filterContext)
    {
    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        if (!_identity.Roles.Contains(_roleName))
            filterContext.Result = new HttpUnauthorizedResult();
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用Ninject.这是我的控制器.我正在尝试将注入的服务放入我的ActionFilter中,以便不依赖HttpContext于我,而是依赖于我的IBusinessIdentity.

IBusinessIdentity获取注入HttpContext.User.Identity`.它会执行一些数据库调用并获取userRoles.

public class HomeController : Controller
{
    readonly IBusinessIdentity _identity;

    public HomeController(IBusinessIdentity identity)
    {
        this._identity= identity;
    }

    [IsAdmin("Admin", _identity)]
    public ActionResult Index()
    {
        return View();  
    }
}
Run Code Online (Sandbox Code Playgroud)

这不起作用,当我尝试在编译时将"identity"放在actionfilter构造函数中时,我遇到编译器错误.

非静态字段,方法或属性需要对象引用

我需要这个,因为我打算用身份测试各种权限.

我想在控制器实例化之后要做一些反思.我对如何做到这一点有一个非常模糊的想法.

我正在使用ASP.NET MVC 5,我没有kernel.bindfilter.我不能使用旧版本.

我很清楚这个黑客.

为单个控制器重复调用动作过滤器构造函数

https://github.com/ninject/Ninject.Web.Mvc/wiki/Conditional-bindings-for-filters

如何使用Ninject for MVC 5实现相同的效果.

编辑:大规模失败

我忘了包括:

using Ninject.Web.Mvc.FilterBindingSyntax;
Run Code Online (Sandbox Code Playgroud)

现在一切都按照上面的链接解释了.

现在我需要弄清楚如何在过滤器构造函数中注入"roleName"字符串.虽然我认为只是为每个角色构建一个过滤器.我稍后会发布完整的代码.

Nig*_*888 10

虽然您的问题不同,但答案与问题完全相同.

DI友好属性永远不应该定义任何行为.您需要将行为分离到一个单独的过滤器中,该过滤器可以在应用程序启动时注入其依赖项.这可以通过将动作过滤器属性分为两部分来完成.

  1. 一个属性,不包含用于标记控制器和操作方法的行为.
  2. 一个DI友好类,它实现IActionFilter和/或IAuthenticationFilter,其中包含扫描实现所需的行为,以检查属性.

不要让微软的ActionFilterAttribute营销欺骗你.这种方法完全不符合DI.