Matt Matt - 1 year ago 87
C# Question

MVC - Layout keeps displaying menus after logging out

I'm currently working on a website that follows a guide on plural-sight.
I'm having two main issues with the web application:

  1. After logging out, items that are under the following
    statement are still showing up:

    @if (User.Identity.IsAuthenticated)
    <li class="nav-item btn-group">
    <a class="nav-link dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fa fa-user"></i> <span class="hidden-sm-down"> @User.Identity.Name </span> </a>
    <div class="dropdown-menu">
    <a class="dropdown-item" asp-controller="Account" asp-action="Account"> Account <i class="fa fa-user" aria-hidden="true"></i> </a>
    <a class="dropdown-item" asp-controller="Settings" asp-action="Settings"> Settings <i class="fa fa-gear" aria-hidden="true"></i> </a>
    <div class="dropdown-divider"></div>
    <a class="dropdown-item" asp-controller="Logout" asp-action="Logout"> Logout <i class="fa fa-sign-out" aria-hidden="true"></i> </a>

  2. The second problem is hiding menus from users who are logged in:

    @if (!User.Identity.IsAuthenticated)
    <li class="nav-item @(ViewContext.RouteData.Values["Controller"].ToString() == "Contact" ? "active" : "")">
    <a class="nav-link" asp-controller="Contact" asp-action="Contact">Contact</a>
    <li class="nav-item @(ViewContext.RouteData.Values["Controller"].ToString() == "About" ? "active" : "")">
    <a class="nav-link" asp-controller="About" asp-action="About">About</a>

returns a Boolean I'm not sure why this wouldn't work.

Picture of my NavBar displaying menus after login out

I'll provide more details if needed. Thank you in advance!

Answer Source

When you're using SignOut(), the user is logged off on the next (http)request.


  1. Do a redirect
  2. Or Force log out. The seems only be possible in non-core ASP.Net: To log off immediately, clear the User property with a default value:

     //log off immediately
     HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download