正如@Marcus 所说,您应该使用属性。操作开始时,您可以检查用户的角色,他是否有权访问:
public class AttributeForTestAttribute : ActionFilterAttribute
{
public int RoleCanAccess { get; set; }
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
//your validation here..
//for example:
if(_currentUser.Role < RoleHasAccess )
{
//user has not access to this action, redirect him to home page.
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Home" }, { "action", "Index" }, { "returnUri", filterContext.HttpContext.Request.RawUrl } });
}
else
{
// user has access to this action
}
}
}
在控制器中使用您的属性:
[AttributeForTest(RoleHasAccess = 2)]
public ActionResult SaveProduct(Product product)
{
}