加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

ASP.NET MVC 5中的Actionfilter注入

发布时间:2020-12-16 07:29:30 所属栏目:asp.Net 来源:网络整理
导读:我有一个简单的过滤器. public class IsAdmin : ActionFilterAttribute,IAuthenticationFilter{ private string _roleName; IBusinessIdentity _identity; public IsAdmin(string roleName,IBusinessIdentity identity) { this._roleName = roleName; this._
我有一个简单的过滤器.

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();
    }
}

我正在使用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();  
    }
}

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

An object reference is required for the non-static field,method,or property

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

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

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

我很清楚这个黑客.

Action filter constructor being called repeatedly for single controller

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

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

编辑:大规模失败

我忘了包括:

using Ninject.Web.Mvc.FilterBindingSyntax;

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

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

解决方法

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

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读