2

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?

Asaf Sitner
  • 599
  • 1
  • 10
  • 18
  • Apparently the Session object doesn't get set because the Login action gets circumvented by the authentication system. Can I edit it, or do I have to put a check and set the Session value in every controller? – Asaf Sitner Oct 15 '13 at 15:29
  • Aaaaand I can't reference the Session object on the first request the user makes. Is there a way to force Session object creation? – Asaf Sitner Oct 15 '13 at 16:04

0 Answers0