Ayudante incorporado para analizar User.Identity.Name en DomainUsername
¿Hay alguna utilidad o ayudante incorporada para analizar HttpContext.Current.User.Identity.Name
, por ejemplo, domain\user
para obtener por separado el nombre de dominio si existe y el usuario?
¿O hay alguna otra clase que lo haga?
Entiendo que es muy fácil llamar String.Split("\")
pero simplemente interesante
8 answers
Esto es mejor ( más fácil de usar, sin oportunidad de NullReferenceExcpetion
y cumple con las pautas de codificación de MS sobre el tratamiento de cadenas vacías y nulas por igual):
public static class Extensions
{
public static string GetDomain(this IIdentity identity)
{
string s = identity.Name;
int stop = s.IndexOf("\\");
return (stop > -1) ? s.Substring(0, stop) : string.Empty;
}
public static string GetLogin(this IIdentity identity)
{
string s = identity.Name;
int stop = s.IndexOf("\\");
return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1) : string.Empty;
}
}
Uso:
IIdentity id = HttpContext.Current.User.Identity;
id.GetLogin();
id.GetDomain();
Esto requiere el compilador C# 3.0 (o posterior) y no requiere 3.0.Net para trabajar después de la compilación.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-29 16:45:06
System.Environment.UserDomainName
le da el nombre de dominio solamente
Del mismo modo, System.Environment.UserName
le da el nombre de usuario solo
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-08 21:19:40
var components = User.Identity.Name.Split('\\');
var userName = components.Last()
var domainName = components.Reverse().Skip(1).FirstOrDefault()
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-01 16:21:09
Ustedes también podrían considerar analizar una entrada de cadena como "[email protected]", o "usuario @ dominio".
Esto es lo que estoy haciendo actualmente:
Si la cadena contiene ' \ 'entonces dividir cadena en' \ ' y extraer nombre de usuario y dominio
De lo contrario, si la cadena contiene'@', entonces divida la cadena en ' @ ' y extraiga el nombre de usuario y el dominio
Else tratar cadena como nombre de usuario sin un dominio
Todavía estoy buscando una mejor solución en el caso de que la cadena de entrada no esté en un formato fácil de predecir, es decir, "dominio\usuario@dominio". Estoy pensando en RegEx...
Actualización: Me he corregido. Mi respuesta es un poco fuera de contexto, se refiere al caso general de analizar el nombre de usuario y los dominios fuera de la entrada del usuario, como en el inicio de sesión/inicio de sesión del usuario. Espero que todavía ayude a alguien.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-01 22:24:09
Yo también pienso que no, porque el otro día me hice la misma pregunta :D
Puedes probar:
public static string GetDomain(string s)
{
int stop = s.IndexOf("\\");
return (stop > -1) ? s.Substring(0, stop + 1) : null;
}
public static string GetLogin(string s)
{
int stop = s.IndexOf("\\");
return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1) : null;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-03 15:20:36
No lo creo, porque el Sistema.Seguridad.Principal.WindowsIdentity no contiene tales miembros.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-12-08 13:27:24
Aunque no es un.NET incorporado, siempre se puede invocar P/a CredUIParseUserName. Aquí es un ejemplo de cómo usarlo en. NET.
PD: No parece manejar el "punto", como en ".\username".
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-03 11:16:52
Parece un problema hecho para ser resuelto por expresiones regulares:
public static class UserExtensions
{
public static string GetDomain(this IIdentity identity)
{
Regex.Match(identity.Name, ".*\\\\").ToString()
}
public static string GetLogin(this IIdentity identity)
{
return Regex.Replace(identity.Name, ".*\\\\", "");
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-01 13:19:10