User.Identity.IsAuthenticated是否必要?

时间:2013-12-07 01:20:47

标签: asp.net-mvc authentication asp.net-identity

我一直在使用ASP.NET MVC做一些事情,但我想知道User.Identity.IsAuthenticated有什么用 - 在我信任User.Identity.Name之前我总是需要检查这个,或者是在这种情况下,IsAuthenticated无用吗?

我应该这样做:

public string GetUserName()
{
    if (User.Identity.IsAuthenticated)
        return User.Identity.Name;
    else
        return null;
}

或者会:

public string GetUserName()
{
    return User.Identity.Name;
}
好吗?我通常使用第一种方式(检查只是为了确定),但我从来没有真正理解是否有必要(据我所知,默认的MVC 5模板只检查它本质上是否用户登录)。

谢谢!

1 个答案:

答案 0 :(得分:0)

对于匿名用户(User.Identity.IsAuthenticated == false),User.Identity.Name将返回一个空字符串,因此您可能不需要检查,除非您确实要从方法中返回null

现在,如果User.Identity.IsAuthenticated == false在给定页面上发生,则完全取决于您在应用程序中实现身份验证的方式。

相关问题