ASP.NET MVC 4自定义授权属性与权限代码(无angular色)

我需要在我的MVC 4应用程序中根据用户权限级别(没有angular色,只有权限级别分配给用户的CRUD操作级别)来控制对视图的访问。

示例如下AuthorizeUser将是我的自定义属性ABD我需要像下面一样使用它。

[AuthorizeUser(AccessLevels="Read Invoice, Update Invoice")] public ActionResult UpdateInvoice(int invoiceId) { // some code... return View(); } [AuthorizeUser(AccessLevels="Create Invoice")] public ActionResult CreateNewInvoice() { // some code... return View(); } [AuthorizeUser(AccessLevels="Delete Invoice")] public ActionResult DeleteInvoice(int invoiceId) { // some code... return View(); } 

这可能吗? 怎么样? 提前致谢…

Chatura

我可以使用自定义属性来做到这一点,如下所示。

 [AuthorizeUser(AccessLevel = "Create")] public ActionResult CreateNewInvoice() { //... return View(); } 

自定义属性类如下。

 public class AuthorizeUserAttribute : AuthorizeAttribute { // Custom property public string AccessLevel { get; set; } protected override bool AuthorizeCore(HttpContextBase httpContext) { var isAuthorized = base.AuthorizeCore(httpContext); if (!isAuthorized) { return false; } string privilegeLevels = string.Join("", GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB return privilegeLevels.Contains(this.AccessLevel); } } 

您可以通过重写HandleUnauthorizedRequest方法来redirect未经授权的用户在您的自定义AuthorisationAttribute

 protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary( new { controller = "Error", action = "Unauthorised" }) ); } 

这是对prev的修改。 回答。 主要区别是当用户没有通过authentication时,它使用原来的“HandleUnauthorizedRequest”方法redirect到login页面:

  protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (filterContext.HttpContext.User.Identity.IsAuthenticated) { filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary( new { controller = "Account", action = "Unauthorised" }) ); } else { base.HandleUnauthorizedRequest(filterContext); } }