2011-03-24 34 views
15

要獲取登錄的用戶當前在系統我用這個代碼:如何獲取當前正在訪問ASP.NET應用程序的用戶?

string opl = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString(); 

我上的ASP.NET應用程序,我需要這些信息的工作。所以我把我的應用程序放在服務器上,並嘗試了上面的代碼,並在字符串opl中獲得了「網絡服務」。我需要知道訪問我的ASP.NET應用程序的PC的當前用戶。

回答

12

如果您使用會員,你可以這樣做:Membership.GetUser()

您的代碼返回被分配與ASP.NET的Windows帳戶。

+0

我能找到嗎? – SamekaTV 2011-03-24 09:53:23

+2

System.Web.Security命名空間 – Robert 2011-03-24 09:56:00

+0

我得到:「對象引用未設置爲對象的實例。」 - 錯誤 – SamekaTV 2011-03-24 10:00:03

41

簡單的回答是User = System.Web.HttpContext.Current.User

確保你的web.config具有以下驗證元素。

<configuration> 
    <system.web> 
     <authentication mode="Windows" /> 
     <authorization> 
      <deny users="?"/> 
     </authorization> 
    </system.web> 
</configuration> 

進一步閱讀Recipe: Enabling Windows Authentication within an Intranet ASP.NET Web application

+6

這個如果你正在尋找用戶登錄。具體來說,該字符串是'System.Web.HttpContext.Current.User.Identity.Name' – Nashwan 2011-03-24 09:48:15

+0

現在它不返回任何字符串爲空:s – SamekaTV 2011-03-24 09:53:59

+1

閱讀文章,您需要配置Windows身份驗證。 – BenCr 2011-03-24 10:03:13

13

使用System.Web.HttpContext.Current.User.Identity.Name應該工作。 請檢查服務器上的IIS站點設置由做託管您的網站如下:

  1. 轉到IIS→網站→你的網站→認證

    IIS Settings

  2. 現在檢查匿名訪問已禁用& Windows身份驗證已啓用。

    Authentication

  3. 現在System.Web.HttpContext.Current.User.Identity.Name應該返回是這樣的:

    domain\username

+0

對於MVC C#應用程序,這爲我工作 – akasoggybunz 2017-06-01 17:13:18

4

最好的做法是先檢查Identity.IsAuthenticated屬性,然後拿到usr.UserName這樣的:

string userName = string.Empty; 

if (System.Web.HttpContext.Current != null && 
    System.Web.HttpContext.Current.User.Identity.IsAuthenticated) 
{ 
    System.Web.Security.MembershipUser usr = Membership.GetUser(); 
    if (usr != null) 
    { 
     userName = usr.UserName; 
    } 
} 
2

不要看得太遠。

如果您使用ASP.NET MVC進行開發,您只需將用戶作爲property of the Controller class。因此,如果您在尋找當前用戶的某些型號中迷路了,請嘗試退後並在控制器中獲取相關信息。

在控制器,只需使用:

using Microsoft.AspNet.Identity; 

    ... 

    var userId = User.Identity.GetUserId(); 
    ... 

userId爲字符串。

2

您可以簡單地使用頁面的屬性。有趣的是,您可以在代碼中的任何位置訪問該屬性。

使用此:

在命名空間
HttpContext.Current.User.Identity.Name 
相關問題