2008-12-01 84 views
34

在aspx頁面中,我獲取了具有函數Request.LogonUserIdentity.Name的Windows用戶名。該函數返回格式爲「domain \ user」的字符串。如何在沒有域名的情況下獲取用戶名

是否有一些功能只獲取用戶名,而不訴諸於IndexOfSubstring,像這樣?

public static string StripDomain(string username) 
{ 
    int pos = username.IndexOf('\\'); 
    return pos != -1 ? username.Substring(pos + 1) : username; 
} 

回答

29

我不這麼認爲。我有使用這些方法的用戶名在─

System.Security.Principal.IPrincipal user = System.Web.HttpContext.Current.User; 
System.Security.Principal.IIdentity identity = user.Identity; 
return identity.Name.Substring(identity.Name.IndexOf(@"\") + 1); 

Request.LogonUserIdentity.Name.Substring(Request.LogonUserIdentity.Name.LastIndexOf(@"\") + 1); 
+0

Request.LogonUserIdentity.Name對於登錄表單來說工作得很好,以便在創建使用LDAP的登錄表單時在域上獲取登錄用戶的用戶名。其他的需要Windows認證彈出我相信。 – RandomUs1r 2014-09-09 19:33:39

5

如果您使用的是.NET 3.5,你總是可以創建一個擴展方法的類的WindowsIdentity做這個工作適合你。

public static string NameWithoutDomain(this WindowsIdentity identity) 
{ 
    string[] parts = identity.Name.Split(new char[] { '\\' }); 

    //highly recommend checking parts array for validity here 
    //prior to dereferencing 

    return parts[1]; 
} 

這樣所有你必須在你的代碼的任何地方做的是參考:

Request.LogonUserIdentity.NameWithoutDomain();

1
static class IdentityHelpers 
{ 
    public static string ShortName(this WindowsIdentity Identity) 
    { 
     if (null != Identity) 
     { 
      return Identity.Name.Split(new char[] {'\\'})[1]; 
     } 
     return string.Empty; 
    } 
} 

如果包含此代碼,然後你可以只是這樣做:

WindowsIdentity a = WindowsIdentity.GetCurrent(); 
Console.WriteLine(a.ShortName); 

顯然,在網絡環境中,你就不會寫到控制檯 - 只是舉個例子?

11

獲取部件[1]不是一種安全的方法。我寧願使用LINQ。Last():

WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent(); 
if (windowsIdentity == null) 
    throw new InvalidOperationException("WindowsIdentity is null"); 
string nameWithoutDomain = windowsIdentity.Name.Split('\\').Last(); 
+1

這種方法會給出錯誤的結果,但如果`Name`由於某種原因不包含反斜槓(例如Workgroup?) – 2013-02-12 11:46:05

46

如果您使用Windows身份驗證。 這可以簡單地通過調用System.Environment.UserName來實現,它只會給你用戶名。 如果您只希望使用域名,您可以使用System.Environment.UserDomainName

+0

好的。不知道這個...... – doekman 2013-06-03 20:05:48

相關問題