Search code examples
c#asp.net-mvcasp.net-mvc-5asp.net-identity

ASP.Net MVC 5 Check User Role For _Layout


Hello everyone I am trying to check what Role my user is in with the default setup. I thought I would only need 'User.IsInRole("User")' for in my View but its not so easy. I want to display certain links depending on the role for the user. Here is what I have and I tried a few different options. I have the default setup database and some added tables that dont matter for this part. Request.IsAuthenticated works for login.

I tried user.isinrole and request.isauthenticated but nether worked for this instance with my view

@if (Request.IsAuthenticated)
                    {
                        <li class="nav-item">
                            <a class="nav-link" href="#">Assign Roles</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#">View Roles</a>
                        </li>                        
                        <li class="nav-item">
                            <a class="nav-link" href="#">Reset Password</a>
                        </li>
                    } else if (Request.IsAuthenticated && User.IsInRole("User"))
                    {
                        <li class="nav-item">
                            <a class="nav-link" href="#">user Else clause</a>
                        </li>
                    } else if (Request.IsAuthenticated && User.IsInRole("Guest"))
                    {
                        <li class="nav-item">
                            <a class="nav-link" href="#">guest Else clause</a>
                        </li>
                    } else
                    {
                        <li class="nav-item">
                            <a class="nav-link" href="#">else else!! Else clause</a>
                        </li>
                    }

The 'else' works when no user is logged in.


Solution

  • This is what I ended up doing to for my solution

    @if (User.IsInRole("User"))
    {
        <li class="nav-item">
            <a class="nav-link" href="#">user Else clause</a>
        </li>
    } 
    @if (User.IsInRole("Guest"))
    {
        <li class="nav-item">
            <a class="nav-link" href="#">guest Else clause</a>
        </li>
    }