重用MVC控制器角色授权以显示菜单项

Ric*_*use 6 c# asp.net-mvc-3

我希望重用我当前定义的Controller/Action Authorize属性来指定用户访问角色以显示菜单项(因此用户只能看到他们有权访问的菜单项).

目前,菜单项的显示和控制器/动作授权属性角色是不同的,因此任何更改都需要在两个地方进行更新,这可能在将来容易出错.

我一直在研究自定义授权属性,这是我到目前为止所拥有的:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {
            return false;
        }

        var routeData = httpContext.Request.RequestContext.RouteData;
        string currentAction = routeData.GetRequiredString("action");
        string currentController = routeData.GetRequiredString("controller");

        var currentUserRoles = GetCurrentUserRoles();

        // from the list of menu items, find the menu item with the current action
        // and controller and check the current user's roles entitle access
    }

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

MenuItems基本上由菜单项可用的用户角色,前端显示的文本标签和控制器和动作的URL组成.MenuItems在局部视图中呈现,具体取决于当前用户是否具有显示MenuItem所需的角色.

从我所看到的,我可能需要一个详尽的列表,列出所有控制器操作以及在这两个区域中重用的相关用户角色,是否有更优雅的方法来实现这一目标?

Ric*_*use 3

经过进一步研究,我偶然发现了 AuthorizedActionLink nuget 包。本质上,这是一个基于 ActionLink 的 Html Helper,只有当用户有权访问目标控制器操作时才会显示链接(请参阅https://authorizedactionlink.codeplex.com/)。

因此,@Html.ActionLink()我不使用 ,而是简单地使用 ,@Html.AuthorizedActionLink()并且菜单是根据在控制器/操作级别指定的用户权限构建的:)。

@Html.ActionIsAccessibleToUser(actionName, controllerName)链接周围还有这样的标记,例如<li>可以省略。