我使用的是 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 , 只能包含字母或数字。
所有帐户都是本地帐户,未配置为使用外部登录,例如 facebook 或 Google。
如果您能提供任何帮助,我们将不胜感激,因为我对这个问题进行了广泛的 Google 搜索,除了关于如何将电子邮件地址实现为用户名的教程外,什么也没有找到,我已经完成了。
最佳答案
请学习并遵循这段代码,它有效:
var db = new DBModel();
DBModel context = new DBModel();
var userStore = new UserStore<User>(context);
var userManager = new UserManager<User>(userStore);
userManager.UserValidator = new UserValidator<User>(userManager)
{
AllowOnlyAlphanumericUserNames = false
};
关于c# - 仅当用户电子邮件地址包含破折号时,AddToRole() 才返回 "User name can only contain letters or digits",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27002798/