简体   繁体   中英

How to check if a user is authenticated in ASP.NET Core

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?

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)
...

Try with:

if(User.Identity.IsAuthenticated)
{
    //..
}

If it isn't valid then User.Identity will be null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM