Não pode ficar UserManager de OwinContext em apicontroller
-
20-12-2019 - |
Pergunta
Estou a seguir um exemplo da Microsoft para implementar e-mail de validação com Identidade 2.0.0
Eu estou preso a esta parte
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
Isso funciona em um controller
mas HttpContext
não contém qualquer GetOwinContext
método um ApiController.
Então, eu tentei HttpContext.Current.GetOwinContext()
mas o método GetUserManager
não existe.
Eu não consigo descobrir uma maneira de obter o UserManager
Eu construir em O arranque.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 linha
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
chama a função a seguir para configurar o 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;
}
Como posso aceder a este UserManager
em um ApiController
?
Solução
Eu realmente mal a sua pergunta anterior.Você está apenas faltando alguns usando declarações, eu acho.
O GetOwinContext().GetUserManager<ApplicationUserManager>()
é no Microsoft.AspNet.Identity.Owin
.
De modo a tentar adicionar esta parte:
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity; // Maybe this one too
var manager = HttpContext.Current.GetOwinContext().GetUserManager<UserManager<User>>();
Outras dicas
Este método de extensão pode ser a melhor solução se você deseja teste de unidade com os seus 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 linha de código, salvou meu dia...
var manager =
new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()));
Você pode usá-lo dentro de uma ação de controle para obter uma instância de UserManager.