【发布时间】:2015-03-01 11:50:53
【问题描述】:
我有一个简单的过滤器。
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();
}
}
这不起作用,当我尝试在编译时将“身份”放入 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”字符串。虽然我认为只是为每个角色构建一个过滤器。我稍后会发布整个代码。
【问题讨论】:
-
应该是
readonly IBusinessIdentity _identity和[IsAdmin("Admin", _identity)]? -
是的,对不起,我纠正了我的错误。
-
这行得通吗?我看到一个帖子stackoverflow.com/questions/5809755/… 它说属性参数有一些限制。您的
IBusinessIdentity可以作为参数传递?
标签: asp.net asp.net-mvc dependency-injection inversion-of-control ninject