2011-05-22 242 views
66

我使用形式的驗證下面的方法在我的ASP.NET應用程序如何檢查用戶是否「登錄」?

FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true); 

如何檢查用戶是否登錄或不?我如何獲得登錄用戶的用戶名?檢查它們已通過認證

回答

149

我設法找到正確的一個。在下面。

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 
+28

只需稍微修復一下更安全的代碼:bool val1 =(System.Web.HttpContext.Current.User!= null)&& System.Web.HttpContext .Current.User.Identity.IsAuthenticated – 2013-05-30 04:30:03

+13

在較新版本的C#中,可以使用User?.Identity.IsAuthenticated == true。 – bradlis7 2016-03-17 20:29:26

+0

或'User?.Identity.IsAuthenticated ??假',但@ bradlis7的代碼可能更易於閱讀。 – Michael 2017-12-19 19:19:11

5

最簡單方法是Request.User.IsAuthenticated我認爲(從內存)

+1

以及 「Request.LogonUserIdentity」 類對所有的這些方法和屬性。謝謝你的提示。 – BlueBird 2011-05-22 07:04:58

+1

沒有@beardtwizzle。這顯示了登錄或不登錄的Windows帳戶。即使你的cookies被刪除,你也可以看到窗口帳戶的用戶名和登錄信息。這一個爲我工作。 「bool val1 = System.Web.HttpContext.Current.User.Identity.IsAuthenticated」 – BlueBird 2011-05-22 07:31:08

7

最簡單的方法:

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