Search code examples
c#asp.net-coreasp.net-core-mvc

How to get the current Id of a user to pass to _Layout ASP.NET Core?


I need to pass the Id of the current user to the _Layout master page.

It must be passed to where "asp-route-id"

<a class="nav-link text-dark" asp-controller="Account" asp-action="MyPersonalCabinet" asp-route-id="HERE">My Cabinet</a>

Here is the method:

public async Task<IActionResult> MyPersonalCabinet(string id)
{
    var user = await _userManager.FindByIdAsync(id);
    var userId = _userManager.GetUserId(HttpContext.User);
        
    if (user != null && userId == id)
    {
        return View(user);
    }

    return NotFound();
}        

With var userId = _userManager.GetUserId (HttpContext.User); I get the current id in the method. How do I do something like this to pass this Id to _Layout

I tried to come up with something with ViewBag but it didn't work


Solution

  • You can try injecting userManager in the layout.

    @using Microsoft.AspNetCore.Identity
    @inject UserManager<ApplicationUser> userManager
    

    Then retrieve Id

    <p>@{var user = userManager.GetUserAsync(User);
               var userId = user.Id;} </p>