Get user logged in Asp.Net Core 2.0
How do I catch the user who is logged in to the class ?
I'm trying this way:
public class Teste
{
private readonly UserManager<Usuario> _userManager;
public Teste(UserManager<Usuario> userManager)
{
_userManager = userManager;
}
public async Task<Usuario> GetUser()
{
var user = await _userManager.GetUserAsync(HttpContext.User);
return user;
}
}
But it is not working in the Asp.Net Core 2.0:
4 answers
You can either get value in the class or in the control.
The answer of @Maycon F. Castro , is wrong, you can yes, get the username or ID using ClaimsPrincipal
, see the example below:
Class:
public static class MinhaClasse
{
public static string GetUserId(this ClaimsPrincipal claimsPrincipal)
{
if (claimsPrincipal == null)
{
throw new ArgumentNullException(nameof(claimsPrincipal));
}
return claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
}
public static string GetUserName(this ClaimsPrincipal claimsPrincipal)
{
if (claimsPrincipal == null)
{
throw new ArgumentNullException(nameof(claimsPrincipal));
}
return claimsPrincipal.FindFirst(ClaimTypes.Name)?.Value;
}
}
HomeController:
public IActionResult Index()
{
var id = Content(User.GetUserId()).Content; //"dd76f866-a04b-4517-ba1f-7bf35a1ae2c8"
var name = Content(User.GetUserName()).Content; //[email protected]
return View();
}
Sources : Content, ClaimsPrincipal .
I hope I helped.
Through dependency injection, you can have access to your HttpContext
anywhere in the application that receives objects by injection. Just inject the interface IHttpContextAccessor
.
public class Teste
{
private readonly UserManager<Usuario> _userManager;
private readonly IHttpContextAccessor _httpContextAccessor
public Teste(UserManager<Usuario> userManager, IHttpContextAccessor httpContextAccessor)
{
_userManager = userManager;
_httpContextAccessor = httpContextAccessor;
}
public async Task<Usuario> GetUser()
{
var user = await _userManager.GetUserAsync(_httpContextAccessor.HttpContext.User);
return user;
}
}
Complementing (another option)...
Another option to get the logged in user is to do this directly from controller
private readonly UserManager<Usuario> _userManager;
public SeuController(UserManager<Usuario> userManager)
{
_userManager = userManager;
}
public async Task<IActionResult> Index()
{
Usuariouser = await _userManager.GetUserAsync(User);
return View();
}
Just supplementing with an option that can only be used within a Controller
.
string currentUser = User.Identity.Name;
You can also check if the user is in certain Role
:
if(User.IsInRole("nomeDoSeuRole"))
{
// Seu código
}