Search code examples
asp.net-mvcasp.net-coreasp.net-core-mvcasp.net-identity.net-5

How to get logged user data in ASP.NET Core 5 MVC (.NET 5)?


I'm currently working on an ASP.NET Core 5 MVC web project, I used default created Single User Account generated template for user management. I have applied the migration and it's working fine as expected. I need to get logged user, in .NET 5 Single User Account template AccountController was not visible. I tried following code outside the controller, it's giving null.

public class UserService  
{
    private readonly IHttpContextAccessor _context;

    public UserService(IHttpContextAccessor context)
    {
        _context = context;
    }

    public string GetUser()
    {
       return _context.HttpContext.User?.Identity?.Name;
    }
}

Solution

  • You can see sample code at here https://stackoverflow.com/a/38751842/3728901 (maybe, ASP.NET Core 1, 2, or 3)

    Focus at

    public class MyController : Microsoft.AspNetCore.Mvc.Controller
    
    var id = _userManager.GetUserId(User); // Get user id:
    

    or other way

    private UserManager<ApplicationUser> _userManager;
    
    //class constructor
    public MyController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }
    

    and

    var user = await _userManager.GetUserAsync(User);
    var email = user.Email;
    

    Because this question related .NET 5 therefore I don't consider the question is duplicated. Let's me know or revise small details if has minor changes in .NET 5.