如何查看用户是否“已登录”?


89

我在ASP.NET应用程序中使用以下方法进行表单身份验证

FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);

如何检查用户是否登录?以及如何获取登录用户的用户名?

Answers:


189

我设法找到正确的一个。在下面。

bool val1 = System.Web.HttpContext.Current.User.Identity.IsAuthenticated

编辑

此编辑应归功于@Gianpiero Caretti,他在评论中建议了此。

bool val1 = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated

35
只是一些更安全的代码解决方案:bool val1 =(System.Web.HttpContext.Current.User!= null)&& System.Web.HttpContext.Current.User.Identity.IsAuthenticated
Gianpiero

14
在较新版本的C#中,您可以使用User?.Identity.IsAuthenticated == true
bradlis7 2016年

3
User?.Identity.IsAuthenticated ?? false,但是@ bradlis7的代码可能更易于阅读。
迈克尔”于2007年

13

最简单的方法:

if (Request.IsAuthenticated) ...

6
if (User.Identity.IsAuthenticated)
{
    Page.Title = "Home page for " + User.Identity.Name;
}
else
{
    Page.Title = "Home page for guest user.";
}

看到这种方法没有太多的争议,使用这种方法时是否有需要注意的缺点/问题?Ive决定使用此功能,到目前为止,它似乎仍然有效。
pnizzle

这几乎是一样的顶级投答案,但我们没有使用命名空间在这里

6

Request.User.IsAuthenticated我认为(从内存中)检查它们是否经过身份验证的最简单方法


1
很好的“ Request.LogonUserIdentity”类提供了所有这些方法和属性。谢谢你的提示。
BlueBird 2011年

1
没有@beardtwizzle。这显示是否已登录Windows帐户。即使删除了Cookie,您也可以看到窗口帐户和登录名的用户名。这个为我工作。“布尔val1 = System.Web.HttpContext.Current.User.Identity.IsAuthenticated”
BlueBird 2011年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.