Update: 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.
I have a strongly typed master page that includes information that is based on the currently authenticated user's UserId:
(Guid)Membership.GetUser().ProviderUserKey
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.
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.
Do I have this wrong? Is there another possible cause?
Simple example:
My site's various pages all use a view model object that inherits the master page view model:
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<Models.MasterViewModel>" %>
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:
<%= Model.UserName %>
which I'll put in one of the views, as well as in the site's master view.
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 <%= Model.UserName %> in the master view.
When I remove the <%= Model.UserName %> from the master view, and leave it in the normal view, it redirects as it should, without throwing the error.
I hope this is somewhat more clear.
Edit:
Maybe someone could offer a better way to access the authenticated user's information in the master page?
Edit #2:
I would be very interested to see any example of an authenticated user's info being accessed in the master page...this is a real head-scratcher for me.
Update:
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.