Jerry Nixon @Work: Current user in ASP.NET; it's NOT Environment.UserName

Jerry Nixon on Windows

Wednesday, April 2, 2008

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