Cómo obtener el usuario actual en ASP.NET MVC


En un modelo de formularios, solía obtener el usuario actual conectado por:

Page.CurrentUser

¿Cómo obtengo el usuario actual dentro de una clase controller en ASP.NET ¿MVC?

Author: Peter Mortensen, 2008-11-05

19 answers

Si necesita obtener el usuario desde el controlador, utilice la propiedad User del Controlador. Si lo necesitas desde la vista, rellenaría lo que necesitas específicamente en ViewData, o simplemente podrías llamar a User ya que creo que es una propiedad de ViewPage.

 245
Author: Haacked,
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
2015-07-11 05:55:25

Encontré que User funciona, es decir, User.Identity.Name o User.IsInRole("Administrator").

 182
Author: Peter Mortensen,
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
2017-01-11 18:46:42

Intenta HttpContext.Current.User.

Propiedad Pública Compartida Current () As Sistema.Web.HttpContext
Miembro del Sistema.Web.HttpContext

Resumen:
Obtiene o establece el Sistema.Web.Objeto HttpContext para la solicitud HTTP actual.

Valores de retorno:
sistema.Web.HttpContext para el actual Solicitud HTTP

 55
Author: dove,
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
2017-01-11 18:43:08

Puede obtener el nombre del usuario en ASP.NET MVC4 como esto:

System.Web.HttpContext.Current.User.Identity.Name
 35
Author: radbyx,
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
2017-10-26 07:40:05

Me doy cuenta de que esto es muy viejo, pero solo estoy empezando con ASP.NET MVC, así que pensé en meter mis dos centavos en:

  • Request.IsAuthenticated le indica si el usuario está autenticado.
  • Page.User.Identity le da la identidad del usuario que ha iniciado sesión.
 20
Author: jrb,
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
2017-01-11 18:46:03

Utilizo:

Membership.GetUser().UserName

No estoy seguro de que esto funcione en ASP.NET MVC, pero vale la pena intentarlo:)

 16
Author: Sean,
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
2017-01-11 18:42:30

Nombre de usuario: System.Web.HttpContext.Current.User.Identity.Name

 11
Author: tifoz,
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-09-08 12:50:12

Con el fin de hacer referencia a un ID de usuario creado mediante autenticación simple integrada en ASP.NET MVC 4 en un controlador para fines de filtrado (lo cual es útil si está utilizando database first y Entity Framework 5 para generar enlaces de código primero y sus tablas están estructuradas para que se use una clave foránea para el ID de usuario), puede usar

WebSecurity.CurrentUserId

Una vez que agregue una instrucción using

using System.Web.Security;
 9
Author: MattC,
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
2017-01-11 18:51:36

Nombre de usuario con:

User.Identity.Name

Pero si necesita obtener solo el ID, puede usar:

using Microsoft.AspNet.Identity;

Por lo tanto, puede obtener directamente el ID de usuario:

User.Identity.GetUserId();
 6
Author: Gilberto B. Terra Jr.,
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
2017-01-12 13:44:53

Esta página podría ser lo que buscas:
Usando Page.User.Identity.Name en MVC3

Solo necesitas User.Identity.Name.

 5
Author: heriawan,
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
2017-05-23 12:02:48

Use System.Security.Principal.WindowsIdentity.GetCurrent().Name.

Esto obtendrá el usuario actual de Windows registrado.

 5
Author: Clay Smith,
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
2017-01-11 18:54:26

Por lo que vale, en ASP.NET MVC 3 solo puede usar User que devuelve el usuario para la solicitud actual.

 4
Author: Pieter,
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
2017-01-11 18:47:31

Si está dentro de su página de inicio de sesión, en el evento LoginUser_LoggedIn, por ejemplo, Current.User.Identity.Name devolverá un valor vacío, por lo que debe usar yourLoginControlName.Propiedad UserName.

MembershipUser u = Membership.GetUser(LoginUser.UserName);
 4
Author: live-love,
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
2017-01-11 18:50:24
IPrincipal currentUser = HttpContext.Current.User;
bool writeEnable = currentUser.IsInRole("Administrator") ||
        ...
                   currentUser.IsInRole("Operator");
 3
Author: Gediminas Bukauskas,
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-13 09:13:36
var ticket = FormsAuthentication.Decrypt(
                    HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value);

if (ticket.Expired)
{
    throw new InvalidOperationException("Ticket expired.");
}

IPrincipal user =  (System.Security.Principal.IPrincipal) new RolePrincipal(new FormsIdentity(ticket));
 2
Author: Ognyan Dimitrov,
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
2015-06-24 07:47:06

Si está trabajando en Active Directory en una intranet, aquí hay algunos consejos:

(Windows Server 2012)

Ejecutar cualquier cosa que hable con AD en un servidor web requiere un montón de cambios y paciencia. Ya que cuando se ejecuta en un servidor web vs. local IIS / IIS Express se ejecuta en la identidad del AppPool, por lo que debe configurarlo para suplantar a quien visite el sitio.

Cómo obtener el usuario actual conectado en un active directory cuando su ASP.NET La aplicación MVC es ejecutándose en un servidor web dentro de la red:

// Find currently logged in user
UserPrincipal adUser = null;
using (HostingEnvironment.Impersonate())
{
    var userContext = System.Web.HttpContext.Current.User.Identity;
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["AllowedDomain"], null,
                                                ContextOptions.Negotiate | ContextOptions.SecureSocketLayer);
    adUser = UserPrincipal.FindByIdentity(ctx, userContext.Name);
}
//Then work with 'adUser' from here...

Debe envolver cualquier llamada que tenga que ver con 'contexto de active directory' en lo siguiente para que actúe como el entorno de alojamiento para obtener la información del ANUNCIO:

using (HostingEnvironment.Impersonate()){ ... }

También debes tener impersonate establecido en true en tu web.config:

<system.web>
    <identity impersonate="true" />

Debe tener la autenticación de Windows en la web.config:

<authentication mode="Windows" />
 2
Author: Beau D'Amore,
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
2017-01-11 18:58:56

Podemos usar el siguiente código para obtener el Usuario actual conectado en ASP.Net MVC:

var user= System.Web.HttpContext.Current.User.Identity.GetUserName();

También

var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; //will give 'Domain//UserName'

Environment.UserName - Will Display format : 'Username'
 2
Author: Raj Baral,
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
2018-01-24 00:02:15

Puede utilizar el siguiente código:

Request.LogonUserIdentity.Name;
 2
Author: Rajeev Jayaswal,
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
2018-01-24 00:16:33

En Asp.net Mvc Identidad 2, Puede obtener el nombre de usuario actual por:

var username = System.Web.HttpContext.Current.User.Identity.Name;
 1
Author: Fereydoon Barikzehy,
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
2017-09-29 14:18:46