gpt4 book ai didi

c# - 无法从 apicontroller 中的 OwinContext 获取 UserManager

转载 作者:IT王子 更新时间:2023-10-29 03:42:49 24 4
gpt4 key购买 nike

我正在按照 Microsoft 示例使用 Identity 2.0.0 实现电子邮件验证

我卡在这部分了

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

这在 controller 中有效,但 HttpContextApiController 中不包含任何 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;
}

如何在 ApiController 中访问此 UserManager

最佳答案

我之前真的误解了你的问题。我认为您只是缺少一些 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com