请查看AuthorizeAttribute和特定的角色
用法 :
[Authorize(Roles = "manager,admin")]
public ActionResult myMethod(){
// your code
}
您可以使用该Users
属性并执行以下操作:
[Authorize(Users = UsersHelper.GetAllowedUsers)]
public ActionResult myMethod(){
// your code
}
whereUsersHelper.GetAllowedUsers
是一个带有静态方法的静态类,它以如下格式返回用户:"joe1,admin,momandpop"
更新到 OP 评论:
/// <summary>
/// Checks if the current user is the owner of the Order
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class IsOwnerOfOrderAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (!(filterContext.Result is HttpUnauthorizedResult))
{
// code to check if user has the order he is trying to edit
// if not return this
filterContext.Result = new HttpUnauthorizedResult();
}
}
}
您可以将其放在控制器或特定操作的顶部。