Reputation: 3739
I understand that User.Identity.IsAuthenticated
must be true to check if a user is authenticated. I am however, unsure of which of these properties can be null. So I currently have this code:
if (User?.Identity?.IsAuthenticated == true)
{
// ...
}
Is that correct? Or can any of the null conditional operators be omitted?
Upvotes: 5
Views: 6534
Reputation: 500
If you're using ASP MVC (also aspnet core) the User.Identity is always set. If a user hasn't been authenticated the identity will have no name and IsAuthenticated will be false, so you are safe using
if(User.Identity.IsAuthenticated)
...
Upvotes: 9
Reputation: 306
Try with:
if(User.Identity.IsAuthenticated)
{
//..
}
If it isn't valid then User.Identity will be null.
Upvotes: 1