C# 如何检查用户是否在ASP.NET Core中经过身份验证
我知道C# 如何检查用户是否在ASP.NET Core中经过身份验证,c#,asp.net-core,C#,Asp.net Core,我知道User.Identity.IsAuthenticated必须为true才能检查用户是否经过身份验证。但是,我不确定这些属性中哪些可以为空。所以我现在有这个代码: if (User?.Identity?.IsAuthenticated == true) { // ... } 对吗?或者可以省略任何空条件运算符吗?请尝试: if(User.Identity.IsAuthenticated) { //.. } 如果无效,则User.Identity将为null。如果使用AS
User.Identity.IsAuthenticated
必须为true才能检查用户是否经过身份验证。但是,我不确定这些属性中哪些可以为空。所以我现在有这个代码:
if (User?.Identity?.IsAuthenticated == true)
{
// ...
}
对吗?或者可以省略任何空条件运算符吗?请尝试:
if(User.Identity.IsAuthenticated)
{
//..
}
如果无效,则User.Identity将为null。如果使用ASP MVC(也称为aspnet core),则始终设置User.Identity。如果用户尚未通过身份验证,则标识将没有名称,并且IsAuthenticated将为false,因此您可以安全地使用
if(User.Identity.IsAuthenticated)
...
但如果User.Identity为null,则上述代码将导致NullReferenceException:)您还可以使用Request.IsAuthenticated,这将帮助您检查空用户。