How to get username without domain

前端 未结 7 643
一整个雨季
一整个雨季 2021-02-06 21:12

In an aspx page I get the Windows username with the function Request.LogonUserIdentity.Name. This function returns a string in the format \"domain\\user\".

相关标签:
7条回答
  • 2021-02-06 21:32

    If you are using .NET 3.5 you could always create an extension method to the WindowsIdentity class that does this work for you.

    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];
    }
    

    that way all you have to do anywhere in your code is reference:

    Request.LogonUserIdentity.NameWithoutDomain();

    0 讨论(0)
  • 2021-02-06 21:36

    Getting parts[1] is not a safe approach. I would prefer use LINQ .Last():

    WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
    if (windowsIdentity == null)
        throw new InvalidOperationException("WindowsIdentity is null");
    string nameWithoutDomain = windowsIdentity.Name.Split('\\').Last();
    
    0 讨论(0)
  • 2021-02-06 21:38

    If you are using Windows Authentication. This can simply be achieved by calling System.Environment.UserName which will give you the user name only. If you want only the Domain name you can use System.Environment.UserDomainName

    0 讨论(0)
  • 2021-02-06 21:42

    I don't believe so. I have got the username using these methods before-

    var user = System.Web.HttpContext.Current.User;   
    var name = user.Identity.Name;
    
    var slashIndex = name.IndexOf("\\");
    return slashIndex > -1 
        ? name.Substring(slashIndex  + 1)
        : name.Substring(0, name.IndexOf("@"));
    

    or

    var name = Request.LogonUserIdentity.Name;
    
    var slashIndex = name.IndexOf("\\");
    return slashIndex > -1 
        ? name.Substring(slashIndex  + 1)
        : name.Substring(0, name.IndexOf("@"));
    
    0 讨论(0)
  • 2021-02-06 21:43

    I was suggesting to use regexpes but they would be overkill. [System.String.Split](http://msdn.microsoft.com/en-us/library/b873y76a(VS.80).aspx) do the job.

    string[] parts= username.Split( new char[] {'\\'} );
    return parts[1];
    
    0 讨论(0)
  • 2021-02-06 21:46
    static class IdentityHelpers
    {
        public static string ShortName(this WindowsIdentity Identity)
        {
            if (null != Identity)
            {
                return Identity.Name.Split(new char[] {'\\'})[1];
            }
            return string.Empty;
        }
    }
    

    If you include this code, you could then just do something like:

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

    Obviously in a web environment, you wouldn't write to the console - just an example...

    0 讨论(0)
提交回复
热议问题