title: Where/how to populate session with user stored in cookie data in MVC app on first load?
body: <p>I've got a session variable that stores my entire user object and when the person logs into my site with forms authentication (using the default MVC provided login) I set the Session variable to the user object like so:</p>
  
  <pre><code>FormsAuthentication.SetAuthCookie(user.Username, model.RememberMe);
  SessionUtil.User = user;
  </code></pre>
  
  <p>All my pages are set to work from this Session object, however the problem arises when they check the remember me box. Close their browser, re-open the browser, and go to my site again.  The session is clear at this point, and they didn't log in, but my site still remembers who they are, however all the pages which reference my user object in session break. </p>
  
  <p>I am looking for a way to populate the Session user object with the appropriate data so that in the above scenario the session object would not be empty regardless what page they hit first upon being 'remembered' after visiting my site. Where is a good location to do this? In the application start? In the SessionUtil (right now it's just a static wrapper for session vars)? Base class on the controller? And how do I do that? I've got the logic written to get a user off the username.</p>
  
  <p><strong>Edit:</strong> Well application_start doesn't appear to be a good spot because doing this:</p>
  
  <pre><code>        if (User != null)
          {
              SessionUtil.User = EntityServiceFactory.GetService&lt;UserService&gt;().GetUser(User.Identity.Name);
          }
  </code></pre>
  
  <p>in the method doesn't prevent the problem from happening. I tried doing User.Identity.Name in the if check and then I got a null reference exception, but I am still remembered and logged in when the page actually loads.</p>
  
  <p>Tried the following in Global.asax per Splash-X's comment:</p>
  
  <pre><code>protected void Application_BeginRequest()
      {
          if(User != null)
          {
              SessionUtil.User = EntityServiceFactory.GetService&lt;UserService&gt;().GetUser(User.Identity.Name);
          }
      }
  </code></pre>
  
  <p>This event is running each request, but User is always null. But what I don't get is the default _LogOnPartial code:</p>
  
  <pre><code>@if(Request.IsAuthenticated) {
  &lt;text&gt;&lt;strong&gt;@User.Identity.Name&lt;/strong&gt; [@Html.ActionLink("Profile", "Profile", "Account")]
  [ @Html.ActionLink("Log Off", "LogOff", "Account") ]&lt;/text&gt;
  }
  </code></pre>
  
  <p>is still showing me as logged in and the Username is showing fine there.</p>