I have an ASP.NET Core 2.2 project with the Identity Razor pages scaffold into it. When a user sign in attempt succeeds, I need to pass the logged-in user id and email to the redirecting controller. The Login.cshtml.cs OnPost method return LocalRedirect function only takes a string parameter and I'm not sure how to pass a model or values.
Once a user is logged in I get the complete user object and I've tried using the ViewBag, ViewData, and TempData to pass the id and email to the home controller. ViewBag is not part of Razor pages and with ViewData and TempData the count is always 0 when I check on the break point set in the home controller. I can append the returnUrl to include the id and email as a query string but that seems like I'm going in the wrong direction.
This is part of a larger scenario where I'm maintaining a website that will need to pass around base model properties to each controller. Ultimately I intend for the viewmodels to inherit from a base viewmodel which I'll need the id and email (as a simplified example) values to perform operations with. I'm thinking an optimal solution would allow me to pass a generic model to whatever controller the retrnUrl redirects to. This project is an enhanced upgrade from an ASP.NET MVC project and ASP.NET Core is a little new to me. At this point, my primary focus is passing parameters from the Login OnPost function to the redirecting controller with the correct coding etiquette that best fits the Asp.Net Core approach.
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
var user = await _userManager.FindByEmailAsync(Input.Email);
//ViewData["UserID"] = user.Id;
//TempData["UserID"] = user.Id;
//returnUrl += returnUrl + "?userId=" + user.Id;
return LocalRedirect(returnUrl);
}
}
public HomeController(UserManager<ApplicationUser> userManager, IConfiguration configuration)
{
string id = ViewData["UserID"] != null ? ViewData["UserID"].ToString() : "";
//string id2 = TempData["UserID"] != null ? TempData["UserID"].ToString() : "";
_userManager = userManager;
_configuration = configuration;
}
Aside from not being sure about how to pass the data with a model, the ViewData and TempData is always empty. I at least expected to be able to use either of those but I think a model would be the correct usage here. Can someone please suggest the correct approach to proceed?