Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/198.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何检查用户是否在ASP.NET Core中经过身份验证_C#_Asp.net Core - Fatal编程技术网

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,这将帮助您检查空用户。