3
I need to get the logged-in user to log in, thus including which user included in the table, made changes, and delete. I’m learning the language, and I still have many doubts.
This is my Accountcontroller controller:
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger _logger;
public AccountController(SignInManager<ApplicationUser> signInManager, ILogger<AccountController> logger)
{
_signInManager = signInManager;
_logger = logger;
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
_logger.LogInformation("User logged out.");
return RedirectToPage("./Index");
}
But how can I get the logged in user to log in? If it was in a webforms, or winforms, I would have the log table, and I would do the Insert right after the user action. Would it be the same way? And how to get the id and name of the user who is logged in, to do the Insert on all pages? Besides the log, I need to include in some tables, the user who did the action too, how to do this ?
Edit: This is the way you log in:
public class LoginModel : PageModel
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger<LoginModel> _logger;
private readonly ApplicationDbContext _db;
private readonly UserManager<ApplicationUser> _userManager;
public LoginModel(SignInManager<ApplicationUser> signInManager, ILogger<LoginModel> logger,
ApplicationDbContext db, UserManager<ApplicationUser> userManager)
{
_signInManager = signInManager;
_logger = logger;
_db = db;
_userManager = userManager;
}
[BindProperty]
public InputModel Input { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public string ReturnUrl { get; set; }
[TempData]
public string ErrorMessage { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public async Task OnGetAsync(string returnUrl = null)
{
if (!string.IsNullOrEmpty(ErrorMessage))
{
ModelState.AddModelError(string.Empty, ErrorMessage);
}
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
ReturnUrl = returnUrl;
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
ReturnUrl = returnUrl;
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
var user = await _userManager.FindByEmailAsync(Input.Email);
//var count = _db.ShoppingCart.Where(u => u.ApplicationUserId == user.Id).ToList().Count;
//HttpContext.Session.SetInt32("CartCount", count);
_logger.LogInformation("User logged in.");
return LocalRedirect(Url.GetLocalUrl(returnUrl));
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Page();
}
}
// If we got this far, something failed, redisplay form
return Page();
}
}
Edit: I did like this: I added this line in the page controller:
private readonly UserManager<ApplicationUser> _userManager;
And I’m trying to get the user id like this:
ApplicationUser user = await _userManager.GetUserAsync(User);
Id = user.Id;
It returns me this error:
Object Reference not set to an instance of an Object.
In this line:
ApplicationUser user = await _userManager.GetUserAsync(User);
Edit: Controller is this:
[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");
}
}
Please avoid long discussions in the comments; your talk was moved to the chat
– Maniero