具有 Azure AD 角色的 MVC Webapp hide/show 网站选项卡

MVC Webapp hide/show website tabs with Azure AD Roles

我有一个 MVC WebApp,我在其中成功验证并将 Azure AD 角色拉入我的应用程序。如何根据该角色在我的 _Layout.cshtml 文件中显示或隐藏 'home' 'about' 等导航栏选项卡?

我可以使用 [Authorize(Roles = "")] 在控制器中授权页面,但我想隐藏在导航栏级别。我缺少哪几行代码才能使其动态化?

这是我的 _Layout.cshtml 文件中的代码,我希望实现此目的:

        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            @Html.ActionLink("My Project", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li>@Html.ActionLink("Home", "Index", "Home")</li>
                <li>@Html.ActionLink("About", "About", "Home")</li>
                <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
            </ul>
            @Html.Partial("_LoginPartial")
        </div>

在此先感谢您的帮助!

在 MVC 上,您有 User 对象,它为您提供有关已登录用户的信息。只需使用 User.IsInRole(roleName) 方法,它应该可以工作。

示例:

<div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        @Html.ActionLink("My Project", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
    </div>
    <div class="navbar-collapse collapse">
        <ul class="nav navbar-nav">
            <li>@Html.ActionLink("Home", "Index", "Home")</li>
            <li>@Html.ActionLink("About", "About", "Home")</li>
            @if(User.IsInRole("Admin"))
            {
                //Only the user with "Admin" role can see this
                <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
            }
        </ul>
        @Html.Partial("_LoginPartial")
    </div>