Hiding links from certain roles in ASP.NET MVC5

后端 未结 1 1104
失恋的感觉
失恋的感觉 2021-02-07 12:39

So this may sound a dumb question, but how do I show a link only for an admin user?

Suppose an ordinary user sees the following links:
Home / About / Contact

1条回答
  •  情歌与酒
    2021-02-07 13:08

    Depending on what sort of Membership/User provider you are using, you should just be able to check directly from the View if the user is logged in and in the specific role.

    So you would end up with something like;

    @Html.ActionLink("Index", "Home") 
    @Html.ActionLink("About", "Home") 
    @Html.ActionLink("Contact", "Home") 
    @if ( User.Identity.IsAuthenticated ){
        if ( User.IsInRole("Admin") ){
            @Html.ActionLink("Admin", "AdminController")        
        }
    }
    

    And remember to add [Authorize] attribute to your Admin action method:

    [Authorize(Roles="Admin")]
    public ActionResult Admin()
    {
        // ...
        return View();
    }
    

    0 讨论(0)
提交回复
热议问题