简体   繁体   中英

Storing user data after authentication with MVC4

I am creating a simple login using ASP.NET MVC4 / Razor. I need custom logic, so here's what I have so far:

public class User
   {
      [Required]
      [Display(Name = "User name")]
      public string UserName { get; set; }

      [Required]
      [DataType(DataType.Password)]
      [Display(Name = "Password")]
      public string Password { get; set; }

      public int UserID { get; set; }
      public DateTime LastLogin { get; set; }

      public bool IsValid(string username, string password)
      {
         if(MyCustomLogic.isValidUser(username, password)){
            // Set other variables
            return true;
         } else {
            return false;
         }
      }
   }

In the Controller:

public ActionResult Login(Models.User user)
{
   if (ModelState.IsValid)
   {
      if (user.IsValid(user.UserName, user.Password))
      {
         FormsAuthentication.SetAuthCookie(user.UserName, true);
         // This line is in question
      }
   }
   return View(user);
}

I want to store the Model.User so it can be accessed in the View persistently. Storing it in a Session variable seems to obvious choice, but that will expire independently of the Authentication Cookie .

I think you're asking, how should you store the user for subsequent requests? Convention is to create your own subclass of IPrincipal where you can store whatever you want, and set HttpContext.Current.User to be an instance of this. This question has full examples .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM