所以我正在为一个 mvc 网站设置我的权限。而且我正在执行基于角色的权限,在控制器中执行操作将需要不同的角色,具体取决于操作的目的。我知道最推荐的是 authorizeattribute (因为我希望缓存角色)但是是否可以与 actionfilterattribute 相同?
目前我有一个类似于这样的actionfilterattribute:
public class PermissionRequired : ActionFilterAttribute{
private readonly Role reqrole;
public PermissionRequired(Role reqRole)
{
reqrole = reqRole;
}
public override void OnActionExecuting(ActionExecutingContext filterContext) {
var ctrl = (GeneralController)filterContext.Controller;
if (!ctrl.CurrentUser.InRole(reqrole)) {
//some code to redirect this to a certain page
}
base.OnActionExecuting(filterContext);
}
}
并在 GeneralController 上获取当前用户
public class GeneralController : Controller
private User currentUser;
public User CurrentUser {
get {
if (currentUser != null)
return currentUser;
int currentUserId = Convert.ToInt32(httpContext.User.identity.Name);
if (currentUserId != 0) {
this.currentUser = Tds.Users.FirstOrDefault(u => u.Id == currentUserId)
}
return currentUser;
}
}
在将继承此属性的控制器上
[PermissionRequired(Role.Moderator)]
public class SomeControllerThatNeedsPermission
{
[PermissionRequired(Role.SuperAdmin)]
public ActionResult SomeActionThatNeedsPermission()
{
}
}
因此,感谢任何人的帮助..甚至欢迎评论或想法:D
非常感谢!