Based on the default Identity framework, I'd like to set a session variable when the user logs in to the application.
This works well:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if(ModelState.IsValid)
{
// Validate the password
IdentityResult result = await IdentityManager.Authentication.CheckPasswordAndSignInAsync(AuthenticationManager, model.UserName, model.Password, model.RememberMe);
if(result.Success)
{
//save display name in session view
SiteUser user = await _siteDbContext.Users.SingleOrDefaultAsync(u => u.UserName == model.UserName);
Session["displayName"] = user.DisplayName;
return RedirectToLocal(returnUrl);
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
Which gets displayed in the site's top bar with this line:
@Html.ActionLink(Session["displayName"].ToString(), "Manage", "Account", null)
However, when the I log in with the 'Remember Me' option checked, close the browser and start it again, the session variable doesn't get set, and the page throws a null reference exception.
Digging around a little, it appears as if the /Account/Login
action is set as the default login path, but it never gets called with the cookie authentication.
How can I get in the middle - or right after - of the authentication process and set my session variable?