remove - mvc get windows username without authentication

How to get username without domain (4)

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();

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".

Is there some function to only get the username, without resorting to the IndexOf and Substring, like this?

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

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

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);

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

Extract username from DOMAIN\Username c#

What about User.Identity.GetUserName().Split('\\')[1] ?