プロジェクトでは、mvc3 asp.net アプリケーションを作成しています。私が実装したい機能の 1 つは、疎結合の役割 - アクション属性です。基本的に、管理者ユーザーはロールを作成し、それらをアクションにリンクできる必要があります。
ロール自体はデータベースに格納されています。
次のアプローチの行の何かが機能するかどうか疑問に思っています:
//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();
}
あなたの意見は何ですか?
ありがとう
*UPDATE** こんにちは、私は最近、db コンテキストを使用するときに、上記の設計でいくつかの可能性のある欠落を発見しました。カスタム属性の寿命はコントローラの寿命よりも長いか等しいため、属性をインスタンス化するときに新しいリポジトリを呼び出すと、リポジトリの内部状態が原因で不一致やセキュリティ リークが発生する可能性があります (たとえば 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);
}
お役に立てれば