ASP.NET MVC 5中的Actionfilter注入
我有一个简单的过滤器.
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构造函数中时,我遇到编译器错误.
我需要这个,因为我打算用身份测试各种权限. 我想在控制器实例化之后要做一些反思.我对如何做到这一点有一个非常模糊的想法. 我正在使用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友好属性永远不应该定义任何行为.您需要将行为分离到一个单独的过滤器中,该过滤器可以在应用程序启动时注入其依赖项.这可以通过将动作过滤器属性分为两部分来完成. >一个不包含用于标记控制器和操作方法的行为的属性. 不要让微软的ActionFilterAttribute营销欺骗你.这种方法完全不符合DI. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- List<T>集合的Sort自定义排序用法简单解析
- ASP.NET 4菜单隐藏在包含Silverlight应用程序的div后面
- asp.net-mvc – 使用WebForm的MVC HtmlHelper
- asp.net-web-api – 从ASP.NET WebAPI 2中的头和/或查询字符
- asp.net-core – 无法运行dnx控制台应用程序
- 如何创建ASP.NET Web场?
- asp.net-mvc – 如何使用ASP.NET MVC 5和OWIN获取Facebook的
- asp.net – 从MSDN获取我需要的信息的最快方法是什么?
- asp.net-mvc – 调试ASP.NET MVC绑定的最佳实践
- entity-framework – EF Core:内置Created和Edited时间戳