0

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.

John 'Mark' Smith
  • 2,564
  • 9
  • 43
  • 69

1 Answers1

4

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.

Community
  • 1
  • 1
Tim Rogers
  • 21,297
  • 6
  • 52
  • 68
  • @JohnSmith That would be blackmail. As I had to infer what you meant from your question, and as it doesn't actually contain a question, I'm not convinced it deserves an upvote. – Tim Rogers Mar 24 '14 at 16:17