ASP.net MVC - Get currently logged user role in view

Viewed 5951

I know that there are a lot of topics about this issue but I already tried several solutions and cannot make it work.

So, I am trying to verify the currently logged user role in my view. As referred in the major part of topics about this in StackOverflow, I just have to do:

@User.IsInRole("Admin")

Unfortunately this always returns false even with the "Role" column, in the AspNetUsers table, of the current logged user is populated with "Admin".

I also tried below approach but it says that "UserManager does not exist in current context".

<p>@UserManager.GetRoles(userId)</p>

One of my suspects is that I am not correctly setting the role for the user upon registration. My AspNetRoles table is correctly populated but AspNetUserRoles table is empty.

How can I troubleshoot this to find what is wrong with my application so I can use @User.IsInRole(...) instruction?

Thanks in advance for any help.

3 Answers

This worked perfectly fine for me. Just make sure you've seeded the roles in the database and also the registered user is assigned a role and this should work fine.

        {
            <a asp-action="StudentDashboard" asp-controller="Home">Dashboard</a>
        }
        else
        if (User.IsInRole("College"))
        {
            <a asp-action="CollegeDashboard" asp-controller="Home">Dashboard</a>
        }
        else
        if (User.IsInRole("Manager"))
        {
            <a asp-action="AdminDashboard" asp-controller="Home">Dashboard</a>
        }
        else
        if (User.IsInRole("Admin"))
        {
            <a asp-action="AdminDashboard" asp-controller="Home">Dashboard</a>
        }```


Related