对于一个项目,我正在制作一个 mvc3 asp.net 应用程序。我想要实现的功能之一是松散耦合的角色 - 动作属性。基本上管理员用户应该能够创建角色并将它们与操作链接。
角色本身存储在数据库中。
我想知道以下方法中的某些东西是否可行:
//Definition of a the Attribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyFlexibleAttribute : AuthorizeAttribute
{
private Repository RolesRepository = new Repository();
public String ActionName {get; set;}
public MyFlexibleAttribute()
{
Roles = RolesRepository.getStringRolesSeparatedByComma(ActionName)
}
}
// where in a random controller of a view, I could state
[MyFlexibleAttribute(ActionName = "SpecialAction"]
public ActionResult SpecialAction()
{
return View();
}
你有什么意见?
谢谢
*更新** 嗨,我最近在使用数据库上下文时发现了上述设计的一些可能的缺陷。由于自定义属性的生命周期大于或等于控制器的生命周期,因此在实例化属性时调用新存储库可能会由于存储库的内部状态而导致可能的差异和安全漏洞(如果这使用例如 dbContext )。
EG 数据库已更新,新角色的新操作,但存储库未刷新...
所以它看起来像,在这种情况下:
public ActionTypeName ActionTypeName {get; set;}
private Repository repo;
public CustomAuthorizeAction(ActionTypeName actionTypeName)
{
this.ActionTypeName = actionTypeName;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
//instantiate new instance when calling the OnAuthorization method
this.repo = new Repository();
List<Role> tmp = repo.getRolesLinkedToAction(this.ActionTypeName).ToList();
Roles = String.Join(",", tmp.Select(r => r.Name));
base.OnAuthorization(filterContext);
}
希望这可以帮助