Rick Astley
Rick Astley

Reputation: 125

User.IsInRole("Admin") returning always false in _Layout.cshtml

In layout.cshtml I am checking whether the current user is an admin or not. If so, then a different menu is shown. However, it is always returning false, even when logging in with an admin. I am using the code below:

@if (User.Identity.IsAuthenticated == false)
{
    <li><a href="\Users\Login">Log in</a></li>
    <li><a href="\Users\Register">Register</a></li>
}

else
{
    <li><a href="\Users\Logout">Log out</a></li>
    if (User.IsInRole("Admin"))
    {
        <li><a href="\Users\List">Users List</a></li>
    }
}

Upvotes: 0

Views: 235

Answers (2)

Rick Astley
Rick Astley

Reputation: 125

I just found out what the error was, and believe me, it's really stupid. In my database stored in SSMS, the roles "Admin", and "User" are being stored as "Admin " and "User ", meaning that extra spaces are being added by default. So, when I changed the if (User.IsInRole("Admin")) to if (User.IsInRole("Admin ")), it worked..

Upvotes: 1

Paulo Alves
Paulo Alves

Reputation: 162

Check if you have the rolemanager enabled.

On your web.config or on the constant System.Web.Security.Roles.Enabled

Add to your webconfig

<system.web>
    <roleManager enabled="true" />

Upvotes: 0

Related Questions