Current user in ASP.NET; it's NOT Environment.UserName

If you use Environment.UserName to get the current user in an ASP.Net application you will probably get the "Network Service" because that is the user running IIS (unless another user is running IIS).

If you want to get the current user, just do this:

public static string CurrentUserName
{
get
{
System.Security.Principal.IPrincipal _User;
_User = System.Web.HttpContext.Current.User;
System.Security.Principal.IIdentity _Identity;
_Identity = _User.Identity;
string _Value;
_Value = _Identity.Name.Substring(_Identity.Name.IndexOf(@"\")+1);
return _Value;
}
}
public static string CurrentDomain
{
get
{
System.Security.Principal.IPrincipal _User;
_User = System.Web.HttpContext.Current.User;
System.Security.Principal.IIdentity _Identity;
_Identity = _User.Identity;
string _Value;
_Value = _Identity.Name.Substring(0, _Identity.Name.IndexOf(@"\"));
return _Value;
}
}

2 comments:

Anonymous said...

Hi, Jerry
Seems I encounter similar problem, think you can help.
I am building web services to interface infopath and database, and when I use the Environment.UserName method, I get user name "ASPNET", BTW, I am testing the service on local machine.
In this condition what is the way to get the user name which is used to log on to windows?
Thanks in advance.

Anonymous said...

Sorry forgot to say, I test the method you already provided and it returns empty.

Post a Comment