Reputation: 9562
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.
Upvotes: 0
Views: 1140
Reputation: 73102
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.
No, it won't. SingleOrDefault
will return a single record, no record, or throw an exception if more than one record exists.
Single
will return a single record, or throw an exception if no record or more than one exists.
Could be a few things. Maybe you have case sensitivity issues with the String.Equals
.
It's still possible that Request.IsAuthenticated
(what [Authorize]
looks at) is true, but there is no identity. Particulary true in custom authentication systems (such as attempting to decrypt the forms authentication ticket), and you haven't specified what your using.
Also, make sure the Username
field is backed by a unique index, to provide server-side guarantees that SingleOrDefault
will NEVER throw an exception.
I would put some try/catch in your controller actions, and setup ELMAH to catch the exceptions.
Upvotes: 2
Reputation: 48230
How about:
public Member GetMemberByUsername(string username)
{
if (String.IsNullOrEmpty(username))
return null;
return db.Members.SingleOrDefault(d => d.username.Equals(username));
}
Upvotes: 2