gpt4 book ai didi

asp.net-mvc-4 - ASP.NET MVC 4 自定义授权属性与权限代码(无角色)

转载 作者:行者123 更新时间:2023-12-02 20:19:02 25 4
gpt4 key购买 nike

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

举个例子; AuthorizeUser 下面将是我的自定义属性,我需要像这样使用它:

[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();
}

这样可以吗?

最佳答案

我可以使用自定义属性来完成此操作,如下所示。

[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 方法在自定义 AuthorizationAttribute 中重定向未经授权的用户:

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

关于asp.net-mvc-4 - ASP.NET MVC 4 自定义授权属性与权限代码(无角色),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13264496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com