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

啊,是我看到的 - 我有一個「空」爲必填項。並感謝您的電子郵件驗證程序 - 這似乎工作。這是一個答案,謝謝。但我仍然困惑,爲什麼這個異常(或者實際上我的異步函數中的任何異常)不會將我返回到調試器,我可以在其中檢查對象,但只是將異常寫入瀏覽器...... –

相關問題