DavidJS
DavidJS

Reputation: 457

How to save custom user to User Identity in Asp.NET MVC 5

I have users saved in my database and I am using Entity Framework 6 to retrieve the users in a repository. I am using MVC 5.

What is the best way to store the Logged in user information such as UserID, Email, etc.

Using Session variables or User.Identity?

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model)
{
    if (ModelState.IsValid)
    {

        var user = _uow.UserRepository.FindLogin(model.Email, model.Password);
        if (user != null)
        {
            _uow.UserRepository.UpdateLastLoginDate(user);                    
            _uow.SaveChanges();

            return RedirectToAction("Index", "Administrator");

        }
        else
        {
            ModelState.AddModelError("", "Invalid Email Address or Password.");
        }
    }

    return View(model);
}

Upvotes: 0

Views: 3816

Answers (1)

Stilgar
Stilgar

Reputation: 23551

You don't store this information in the Session. First you need to use the AuthenticationManager.SignIn method as described here - http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity . Then you can use the .GetUserId() extension method to extract the user ID from the Identity object like this:

User.Identity.GetUserId()

You can then use this ID to request the user info from the UserManager. In case you only need the UserName you can use the GetUserName extension method and extract that directly from the Identity object.

Upvotes: 1

Related Questions