. 그러나 여기 여전히 강력한 형식의 모든 것을 가져 오는 동안이 유연성을 유지할 수있는 방법은
는 비트 플래그 사용하는 열거에서 역할을 정의합니다.
[Flags]
public enum AppRole {
Admin = 1,
Moderator = 2,
Editor = 4,
Contributor = 8,
User = 16
}
재정 AuthorizeAttribute을 :
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyAuthorizeAttribute : AuthorizeAttribute {
public AppRole AppRole { get; set; }
public override void OnAuthorization(AuthorizationContext filterContext) {
if (AppRole != 0)
Roles = AppRole.ToString();
base.OnAuthorization(filterContext);
}
}
지금 당신은이 같은 MyAuthorizeAttribute를 사용할 수있는 경우 : 위의 조치는 나열된 역할 중 하나 이상 (관리자, 중재자, 또는 편집기)에있는 사용자에게 권한을 부여합니다
[MyAuthorize(AppRole = AppRole.Admin | AppRole.Moderator | AppRole.Editor)]
public ActionResult Index() {
return View();
}
. MVC의 기본 AuthorizeAttribute와 동일하지만 마법 문자열은 제외됩니다.이 기술을 사용하는 경우
, 여기에 유용 할 수 있습니다 IPrincipal에 확장 메서드는 다음과 같습니다 그렇지 않지만
public ActionResult Index() {
var allowed = User.IsInRole(AppRole.Admin | AppRole.Moderator | AppRole.Editor);
if (!allowed) {
// Do Something
}
return View();
}
단순함으로이 솔루션을 사용했습니다. 하드 코딩 된 문자열을 상수 참조로 바꾸기 만하면되므로 코드 변경이 최소화되었습니다. – MikeWyatt