2008-12-01 122 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

相关问题