Pregunta

Estoy siguiendo un ejemplo de Microsoft para implementar la validación de correo electrónico con Identity 2.0.0

Estoy atrapado en esta parte

public ApplicationUserManager UserManager
{
   get
   {
      return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
   }
   private set
   {
      _userManager = value;
   }
}

Esto funciona en un controller pero HttpContext no contiene ninguna GetOwinContext método en un Controlador API.

Así que lo intenté HttpContext.Current.GetOwinContext() pero el método GetUserManager no existe.

No puedo encontrar una manera de conseguir el UserManager yo construyo Inicio.Auth.cs

// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
    //Configure the db context, user manager and role manager to use a single instance per request
    app.CreatePerOwinContext(ApplicationDbContext.Create);
    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 
    ...
}

esta línea

app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

llama a la siguiente función para configurar el UserManager

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
     var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
     //Configure validation logic for usernames
     manager.UserValidator = new UserValidator<ApplicationUser>(manager)
     {
         AllowOnlyAlphanumericUserNames = false,
         RequireUniqueEmail = true
     };

     // Configure user lockout defaults
     manager.UserLockoutEnabledByDefault = true;
     manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
     manager.MaxFailedAccessAttemptsBeforeLockout = 5;

     manager.EmailService = new EmailService();

     var dataProtectionProvider = options.DataProtectionProvider;
     if (dataProtectionProvider != null)
     {
         manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
     }
     return manager;
}

¿Cómo puedo acceder a esto? UserManager en un ApiController?

¿Fue útil?

Solución

Realmente entendí mal tu pregunta anterior.Creo que te faltan algunas declaraciones de uso.

El GetOwinContext().GetUserManager<ApplicationUserManager>() es en Microsoft.AspNet.Identity.Owin.

Así que intenta agregar esta parte:

using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity; // Maybe this one too

var manager = HttpContext.Current.GetOwinContext().GetUserManager<UserManager<User>>();

Otros consejos

Este método de extensión puede ser una mejor solución si desea realizar una prueba unitaria de sus controladores.

using System;
using System.Net.Http;
using System.Web;
using Microsoft.Owin;

public static IOwinContext GetOwinContext(this HttpRequestMessage request)
{
    var context = request.Properties["MS_HttpContext"] as HttpContextWrapper;
    if (context != null)
    {
        return HttpContextBaseExtensions.GetOwinContext(context.Request);
    }
    return null;
}

Uso:

public ApplicationUserManager UserManager
{
   get
   {
      return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
   }
   private set
   {
      _userManager = value;
   }
}

Esta única línea de código me salvó el día...

       var manager = 
       new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()));

Puede usarlo dentro de una acción de controlador para obtener una instancia de UserManager.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top