我正在跟踪一个Microsoft示例,以使用Identity 2.0.0实现电子邮件验证。
我被困在这部分
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
这可以在
controller
中工作,但是HttpContext
在 ApiController 中不包含任何GetOwinContext
方法。所以我尝试了
HttpContext.Current.GetOwinContext()
,但是方法GetUserManager
不存在。我不知道一种方法来获取在 Startup.Auth.cs 中构建的
UserManager
// 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);
...
}
这条线
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
调用以下函数来配置
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;
}
如何在
UserManager
中访问此ApiController
? 最佳答案
我真的误会了您的问题。我认为您只是缺少一些using语句。GetOwinContext().GetUserManager<ApplicationUserManager>()
在Microsoft.AspNet.Identity.Owin
中。
因此,请尝试添加此部分:
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity; // Maybe this one too
var manager = HttpContext.Current.GetOwinContext().GetUserManager<UserManager<User>>();
关于c# - 无法从apicontroller中的OwinContext获取UserManager,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24001245/