代码之家  ›  专栏  ›  技术社区  ›  doekman

如何获取没有域的用户名

  •  38
  • doekman  · 技术社区  · 16 年前

    在ASPX页面中,我得到了带有函数的Windows用户名 Request.LogonUserIdentity.Name . 此函数返回格式为“域\用户”的字符串。

    是否有一些函数只获取用户名,而不使用 IndexOf Substring 像这样吗?

    public static string StripDomain(string username)
    {
        int pos = username.IndexOf('\\');
        return pos != -1 ? username.Substring(pos + 1) : username;
    }
    
    6 回复  |  直到 10 年前
        1
  •  33
  •   Russ Cam    10 年前

    我不相信。我以前用这些方法得到了用户名-

    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);
    
        2
  •  55
  •   Robin V.    12 年前

    如果您使用的是Windows身份验证。 这可以通过调用 System.Environment.UserName 它只提供用户名。 如果你只想要你能使用的域名 System.Environment.UserDomainName

        3
  •  14
  •   Vitaliy Ulantikov Peter Miehle    10 年前

    获取部件[1]不是一种安全的方法。我更喜欢使用linq.last():

    WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
    if (windowsIdentity == null)
        throw new InvalidOperationException("WindowsIdentity is null");
    string nameWithoutDomain = windowsIdentity.Name.Split('\\').Last();
    
        4
  •  5
  •   Mr. Kraus    16 年前

    如果您使用的是.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();

        5
  •  1
  •   BenAlabaster    16 年前
    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);
    

    显然,在Web环境中,您不会写入控制台-只是一个示例…

        6
  •  0
  •   Johan Buret    16 年前

    我建议使用regexpes,但它们会被过度杀戮。 [系统.string.split]( http://msdn.microsoft.com/en-us/library/b873y76a(VS.80).aspx) 做这项工作。

    string[] parts= username.Split( new char[] {'\\'} );
    return parts[1];