I am using ASP.NET CORE 2.0, and am having to catch the logged-in user ID. This is my Account Controller:
[Route("[controller]/[action]")]
public class AccountController : Controller
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger _logger;
private readonly UserManager<ApplicationUser> _userManager;
public AccountController(SignInManager<ApplicationUser> signInManager, ILogger<AccountController> logger, UserManager<ApplicationUser> userManager)
{
_signInManager = signInManager;
_logger = logger;
_userManager = userManager;
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
_logger.LogInformation("User logged out.");
return RedirectToPage("./Index");
}
}
I'm trying to get the id this way:
ApplicationUser a = new ApplicationUser();
CR.FuncionarioId = a.Id;
But he's returning me a completely different id, why is this happening? I use Identity. Then when I use a.Id, every hour I immediately, even though it is with the same user, it brings a different Id, and it is not bringing the Id that is registered in the AspnetUsers table.
code of the page where I need to get the user id:
protected UserManager<ApplicationUser> UserManager { get; set; }
public RecebimentoModel(CronoParque.Model.ApplicationDbContext context)
{
_context = context;
}
[BindProperty]
public string Message { get; set; }
[BindProperty]
public ContasReceberViewModel ContasReceberVM { get; set; }
public async Task<IActionResult> OnPost()
{
if (ModelState.IsValid)
{
var CR = _context.ContasReceber.Find(ContasReceberVM.ContasReceber.Id);
CR.Quitado = true;
CR.ValorPago = Convert.ToDecimal(ContasReceberVM.ContasReceber.ValorPago.ToString().Replace(",","."));
CR.FormaPagamento = ContasReceberVM.ContasReceber.FormaPagamento;
CR.DataPagamento = DateTime.Now;
CR.FuncionarioId = UserManager.GetUserId(HttpContext.User);
await _context.SaveChangesAsync();
Message = "Pagamento Realizado com Sucesso!";
return RedirectToPage("Index");
}
return RedirectToPage();
}
var user = _userManager.GetUserAsync(User);
var id = user.Result.Id;
try this in your function, it should work :)