How to get username without domain

前端 未结 7 618
一整个雨季
一整个雨季 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: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...

提交回复
热议问题