【发布时间】:2016-05-17 21:08:12
【问题描述】:
通过 Web API 使用“xxx-yyy@gmail.com”等电子邮件注册帐户时,Fiddler 返回以下错误。 请注意,电子邮件也用于用户名,因此两个字段相同。但它在 MVC 本身上注册时有效。
ExceptionMessage=用户创建失败 - 身份异常。错误是:
用户名xx-yyy@gmail.com无效,只能包含字母或数字。
用户对象
var newUser = new ApplicationUser {
UserName = user.Email,
Email = user.Email
};
IdentifyConfig.cs
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) {
RequireUniqueEmail = true,
AllowOnlyAlphanumericUserNames = false
};
我尝试过注释掉 AllowOnlyAlphanumericUserNames,但没有成功。通过将其正确设置为 false 应该允许特殊字符,在我的情况下是连字符 (-)。
API 控制器
// POST: api/auth/register
[ActionName("Register")]
public async Task<HttpResponseMessage> PostRegister(Auth user) {
//dash issue is here.
var userContext = new ApplicationDbContext();
var userStore = new UserStore<ApplicationUser>(userContext);
var userManager = new UserManager<ApplicationUser>(userStore);
var newUser = new ApplicationUser {
UserName = user.Email,
Email = user.Email
};
var result = await userManager.CreateAsync(newUser, user.PasswordHash);
if (result.Succeeded) {
...
解决方案
IdentityConfig.cs 没有变化。唯一的变化是我的 API 控制器。
// POST: api/auth/register
[ActionName("Register")]
public async Task<HttpResponseMessage> PostRegister(Auth user) {
//Changed to the following line
ApplicationUserManager userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var newUser = new ApplicationUser {
UserName = user.Email,
Email = user.Email
};
var result = await userManager.CreateAsync(newUser, user.PasswordHash);
【问题讨论】:
标签: c# asp.net asp.net-mvc asp.net-web-api asp.net-identity