I've been receiving some error reports recently that seem to suggest that sometimes User.Identity.Name is NULL or different to what it should be (the authenticated user's username), even when the page is authenticated:
[Authorize]
[HttpGet]
public ActionResult MyAction()
{
string username = User.Identity.Name;
Member member = memberRepository.GetMemberByUserName(username);
member.something // fails with a null reference exception
}
The GetMemberByUserName() method uses Linq to SQL to retrieve the member.
public Member GetMemberByUsername(string username)
{
if (String.IsNullOrEmpty(username))
return null;
return db.Members.SingleOrDefault(d => d.username.Equals(username));
}
Under which circumstances would this happen? Do I need to check if User.Identity.Name is NULL whenever I use it?
Of course, the User.Identity.Name could be a red herring, and it could be that the database is just not returning anything. I would probably have expected an exception to be thrown if this was the case, though.
EDIT: This is an intermittent issue - it could be that an authenticated user refreshes once, the User.Identity.Name is correct and the member is retrieved, and then on a second refresh, the member is not retrieved.
User.Identity.Namereturns and if such value exist in your database. Hope it'll give you hint.