问题描述
我需要根据我的 MVC 4 应用程序中的用户权限级别(没有角色,只有分配给用户的 CRUD 操作级别的权限级别)来控制对视图的访问.
I need to control the access to views based on users privilege levels (there are no roles, only privilege levels for CRUD operation levels assigned to users) in my MVC 4 application.
举个例子;AuthorizeUser 下面将是我的自定义属性,我需要像这样使用它:
As an example; below the AuthorizeUser will be my custom attribute and I need to use it like this:
[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();
}
可以这样做吗?
推荐答案
我可以使用自定义属性来做到这一点,如下所示.
I could do this with a custom attribute as follows.
[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
方法在您的自定义 AuthorisationAttribute
中重定向未经授权的用户:
You can redirect an unauthorised user in your custom AuthorisationAttribute
by overriding the HandleUnauthorizedRequest
method:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{
controller = "Error",
action = "Unauthorised"
})
);
}
这篇关于带有权限代码的 ASP.NET MVC 4 自定义授权属性(无角色)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!