gpt4 book ai didi

c# - AddToRole 失败并在用户名中输入 + 号?

转载 作者:太空宇宙 更新时间:2023-11-03 19:00:57 24 4
gpt4 key购买 nike

我正在使用它来将新创建的用户添加到角色:

var db = new ApplicationDbContext();
ApplicationDbContext context = new ApplicationDbContext();
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);

userManager.AddToRole(user.Id, model.UserRole);

在我的解决方案中,用户名 = 电子邮件。

我发现,当用户名/电子邮件包含符号(+、- 或类似符号)时,它不会将用户添加到角色。我收到的错误是“用户名 x 无效,只能包含字母或数字。”。用户已成功添加,只是 AddToRole 失败了。

但我不知道为什么。

AllowOnlyAlphanumericUserNames 在 IdentityConfig.cs 中设置为 false

有什么想法吗?

最佳答案

我能想到两种可能的解决方案。

1.) 关注the solution you linked in the comments通过将您的代码示例编辑为:

var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
userManager.AddToRole(user.Id, model.UserRole);

2.) 在您的 userManager 中重新创建 UserValidator 并再次尝试 AddToRole:

var db = new ApplicationDbContext();
ApplicationDbContext context = new ApplicationDbContext();
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
userManager.UserValidator = new UserValidator<ApplicationUser>(userManager) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true };
userManager.AddToRole(user.Id, model.UserRole);

关于c# - AddToRole 失败并在用户名中输入 + 号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36284629/

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