【发布时间】:2020-06-20 17:49:51
【问题描述】:
我使用的是 Asp.Net Identity 2.0,配置为用户的电子邮件地址也是用户名,所以在 IdentityConfig 中,我在 ApplicationUserManager 构造函数中设置了AllowOnlyAlphanumericUserNames = false:
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
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
};
// ... other options removed
}
}
我在页面中使用此代码以供工作人员搜索用户,并在所有可用角色的GridView中选中复选框时,将角色添加到用户帐户中:
//protected UserManager<ApplicationUser> um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
//changed this to call the ApplicationUserManager instead of UserManager to make sure AllowOnlyAlphanumericUserName = false is called, but still no luck
protected ApplicationUserManager um = new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()));
protected void cbRole_CheckChanged(object sender, EventArgs e)
{
string UserName = lblUsername.Text;
if (!String.IsNullOrEmpty(UserName))
{
CheckBox cb = (CheckBox)sender;
GridViewRow row = (GridViewRow)cb.NamingContainer;
string Role = row.Cells[1].Text;
if (cb.Checked)
{
var user = um.FindByName(UserName);
var UserResult = um.AddToRole(user.Id, Role);
if (UserResult.Succeeded)
{
lblRoles.Text = "The <b>" + Role + "</b> role has been added for " + UserName;
}
else
{
foreach (var error in UserResult.Errors)
lblRoles.Text += error; //<-- RETURNS ERROR: "User name <email address> is invalid, can only contain letters or digits." If <email address> contains a dash (-).
}
}
else
{
um.RemoveFromRole(hfAspUserID.Value, Role);
lblRoles.Text = "The <b>" + Role + "</b> role has been removed for " + UserName;
}
}
}
它通常可以完美运行。但是,只要用户的用户名中有破折号,例如“users.name@domain-name.com”,AddToRole() 函数就会返回错误 User name users.name@domain-name.com is invalid, can only contain letters or digits.
所有帐户都是本地帐户,未配置为使用外部登录,例如 facebook 或 Google。
您能提供的任何帮助将不胜感激,因为我对这个问题的广泛谷歌搜索除了关于如何将电子邮件地址实现为用户名的教程之外没有其他任何内容,我已经完成了。
【问题讨论】:
-
调用 cbRole_CheckChanged 方法时,您的 AllowOnlyAlphanumericUserNames = false 似乎未执行。您将 AllowOnlyAlphanumericUserNames = false 属性放在哪里,当您调用 AddToRole() 时必须已经调用它。
-
在ApplicationUserManager类中...我已经在上面添加了。
-
实际上你更新的代码也没有调用你需要的,我认为这已经在 owin statup 上调用了,所以使用该上下文来获取 UserManager,如下所述。
标签: c# asp.net asp.net-identity