基于当前用户的"角色"动态构建ASP.NET MVC主页面菜单

Nat*_*ate 15 .net c# asp.net security asp.net-mvc

我见过一些类似的问题,但没有一个看起来像我正在尝试做的事情.

这是我当前的实施,没有任何安全性:

<div id="menucontainer">
    <ul id="menu">              
        <li><%= Html.ActionLink("Main List", "Index", "AController")%></li>
        <li><%= Html.ActionLink("Product List", "Index", "BController")%></li>
        <li><%= Html.ActionLink("Company List", "Index", "CController")%></li>
        <li><%= Html.ActionLink("User List", "Index", "DController")%></li>
    </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

这很好,以上工作.我在Actions for CController和DController上设置[授权]属性以防止未经授权的访问 - 但我想从菜单中删除那些没有正确角色的用户,因为当他们看到它并点击时在它上面它告诉他们他们没有许可,他们会想要它.如果他们不知道那里,那对所有参与者来说都更好......

这样的事情最终是我想要达到的目标,但我正在寻找更多MVC风味的方法,其中"视图"是"愚蠢的":

<div id="menucontainer">
    <ul id="menu">              
        <li><%= Html.ActionLink("Main List", "Index", "AController")%></li>
        <li><%= Html.ActionLink("Product List", "Index", "BController")%></li>
        <% If(Role = Roles.Admin) { %>
        <li><%= Html.ActionLink("Company List", "Index", "CController")%></li>
        <li><%= Html.ActionLink("User List", "Index", "DController")%></li>
        <% } %>
    </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

jer*_*enh 15

我做过这样的事情:

  • 为我的控制器使用公共基类('layer supertype')
  • 在BaseController中,重写OnActionExecuted(你也可以为此定义一个ActionFilter属性)

像这样的东西:

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // build list of menu items based on user's permissions, and add it to ViewData
        IEnumerable<MenuItem> menu = BuildMenu(); 
        ViewData["Menu"] = menu;
    }
Run Code Online (Sandbox Code Playgroud)

在母版页中:

    <% var model = ViewData["Menu"] as IEnumerable<MenuItem>; %>
    <% Html.RenderPartial("Menu", model); %>
Run Code Online (Sandbox Code Playgroud)

(注意:实际上,我有一个MasterViewModel,其中包含菜单模型)

  • @jeroenh:什么是ao? (2认同)
  • 嘿,我觉得总共n00b,但对我来说这是一个新的.谢谢. (2认同)