title: ASP.NET MVC2 master page and authentication
body: <p><strong>Update:</strong>  I can't delete this question, because the answer has been upvoted, yet it is not at all the answer to what I'm asking.  I'd like to delete this, as it has been a week with no answer, and it's just dragging down my accept %.  Thanks.</p>
  
  <p>I have a strongly typed master page that includes information that is based on the currently authenticated user's UserId:</p>
  
  <pre><code>(Guid)Membership.GetUser().ProviderUserKey
  </code></pre>
  
  <p>Every other normal action/view would require the user to be authenticated prior to it being viewed, which means the user's information is guaranteed to be available.</p>
  
  <p>The problem is, I'm only getting null reference exceptions when I attempt to access the user's info. from the site's master page. I'm guessing this is because there isn't such thing as an [Authorize] attribute that applies to master pages.</p>
  
  <p>Do I have this wrong?  Is there another possible cause?</p>
  
  <p>Simple example:</p>
  
  <p>My site's various pages all use a view model object that inherits the master page view model:</p>
  
  <pre><code>&lt;%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage&lt;Models.MasterViewModel&gt;" %&gt;
  </code></pre>
  
  <p>the authenticated user object is a property of this base view model.  All pages require authentication, so anyone who isn't is redirected to the login view, which has been working flawlessly.  So a simple attempt to make use of a user's property in a view is thus:</p>
  
  <pre><code>&lt;%= Model.UserName %&gt;
  </code></pre>
  
  <p>which I'll put in one of the views, as well as in the site's master view.</p>
  
  <p>When the user is already authenticated, all works as it should, with the UserName being printed twice on the page.  When the auth ticket is expired, or a new user comes along however, the page will not redirect to the login, but instead generate an exception that complains of a null reference coming from the &lt;%= Model.UserName %> in the master view.</p>
  
  <p>When I remove the &lt;%= Model.UserName %> from the master view, and leave it in the normal view, it redirects as it should, without throwing the error.</p>
  
  <p>I hope this is somewhat more clear.</p>
  
  <p>Edit:</p>
  
  <p>Maybe someone could offer a better way to access the authenticated user's information in the master page?</p>
  
  <p>Edit #2:</p>
  
  <p>I would be very interested to see <em>any</em> example of an authenticated user's info being accessed in the master page...this is a real head-scratcher for me.</p>
  
  <p><strong>Update:</strong></p>
  
  <p>I haven't accepted the answer because I'm quite familiar with how I can test whether or not a user is authenticated.  I am curious to know why no redirection to the login page is taking place. </p>