title: How can I make accessing my custom IPrincipal easier in ASP.NET MVC?
body: <p>I've written a custom principal object which contains a few additional fields (email and userid in addition to the username).</p>
  
  <p>In order to access these properties I have to cast the Context.User object as my custom principal.</p>
  
  <pre><code>@Html.GetGravitarImage((User as CustomPrincipal).Email)
  </code></pre>
  
  <p>This custom principal is created / deserialized via the Application_AuthenticateRequest in my global.ascx.  You can see this question I asked <a href="https://stackoverflow.com/questions/7020323/where-can-i-store-email-and-userid-in-my-asp-net-mvc-application-so-i-dont-have">here</a> for more information.</p>
  
  <pre><code>private void Application_AuthenticateRequest(Object source, EventArgs e)
  {
      var application = (HttpApplication)source;
      var context = application.Context;
  
      // Get the authentication cookie
      string cookieName = FormsAuthentication.FormsCookieName;
      HttpCookie authCookie = context.Request.Cookies[cookieName];
      if (authCookie == null)
          return;
  
      var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
      context.User = CustomPrincipal.CreatePrincipalFromCookieData(authTicket.UserData);
  }
  </code></pre>
  
  <p>However, if a user isn't authenticated, then my cast to CustomPrincipal will fail (because it won't be injected in the method above) and the result of the (User as CustomPrincipal) will return null, thus giving me a null reference exception when my method above attempts to get the email.</p>
  
  <p>What would be a clean solution to this problem?  I want to make accessing my custom principal easy and having to do the following seems cumbersome:</p>
  
  <pre><code>@Html.GetGravitarIcon((User is CustomPrincipal) ? (User as CustomPrincipal).Email : "Default Email")
  </code></pre>
  
  <p>Is this the only way to handle this situation?</p>