2

我正在使用Asp.net Identity 1.0并希望使用电子邮件地址作为'用户名'。ASP.NET身份:仅允许字母数字用户名实现

研究后,我发现这个帖子这似乎提出一个解决方案:AllowOnlyAlphanumericUserNames - how to set it? (RC to RTM breaking change) ASP.NET Identity

因此,我实现(我用vb.net)代码:

Public Class AccountController 
Inherits Controller 

Public Sub New() 
    Me.New(New UserManager(Of ApplicationUser)(New UserStore(Of ApplicationUser)(New ApplicationDbContext()))) 
End Sub 

Public Sub New(manager As UserManager(Of ApplicationUser)) 
    UserManager = manager 
    UserManager.UserValidator = New UserValidator(Of ApplicationUser)(UserManager) With {.AllowOnlyAlphanumericUserNames = False} 
End Sub 

Public Property UserManager As UserManager(Of ApplicationUser) 

然而,当我的代码呼吁的UserManager:

Dim result = Await UserManager.CreateAsync(user, acct.password) 

我得到的调试器外部的异常:

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

Source Error:

Dim result = Await UserManager.CreateAsync(user, acct.password) Line 294:
If result.Succeeded Then Trace.WriteLine("Succeeded creating: " + acct.username)

Stack Trace:

[DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.]
System.Data.Entity.Internal.InternalContext.SaveChangesAsync(CancellationToken cancellationToken) +219
System.Data.Entity.Internal.LazyInternalContext.SaveChangesAsync(CancellationToken cancellationToken) +66
System.Data.Entity.DbContext.SaveChangesAsync(CancellationToken cancellationToken) +60
System.Data.Entity.DbContext.SaveChangesAsync() +63
Microsoft.AspNet.Identity.EntityFramework.d__0.MoveNext() etc

由于调试器没有捕获异常,所以我无法看到'EntityValidationErrors'是什么。但是,在插入我的uservalidator之前,我能够捕获标准的“非字母数字不允许”异常。

任何有关我在做什么错的任何想法?谢谢。

回答

1

当实体框架将实体保存到数据库时,发生错误。你应该阅读Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

BTW你想使用一个电子邮件地址作为用户名,所以要使用正确的UserValidator

Public Class EmailUserValidator(Of TUser As IUser) 
    Implements IIdentityValidator(Of TUser) 

    Public Function ValidateAsync(user As TUser) As Task(Of IdentityResult) Implements IIdentityValidator(Of TUser).ValidateAsync 
     Try 
      Dim address = New MailAddress(user.UserName) 
      Return Task.FromResult(New IdentityResult()) 
     Catch 
      Return Task.FromResult(New IdentityResult("Invalid Email.")) 
     End Try 
    End Function 
End Class 
+0

啊,是我看到的 - 我有一个“空”为必填项。并感谢您的电子邮件验证程序 - 这似乎工作。这是一个答案,谢谢。但我仍然困惑,为什么这个异常(或者实际上我的异步函数中的任何异常)不会将我返回到调试器,我可以在其中检查对象,但只是将异常写入浏览器...... –

相关问题