2014-03-13 68 views
1

我設置的值MinimunLenghtValidator修改ApplicationUserManager類我怎樣才能得到MinimumLengthValidator的RequiredLength值(Microsoft.AspNet.Identity與密碼)

public class ApplicationUserManager : UserManager<ApplicationUser> 
{ 
    public ApplicationUserManager() : base(new UserStore<ApplicationUser>(new DataContext())) 
    { 
     PasswordValidator = new MinimumLengthValidator(8); 
    } 
} 

現在,我希望檢索值使用,例如,在AccountViewModel驗證(放眼整個StringLength線)

[Required] 
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = IWANTTHEVALUEHERE)] 
    [DataType(DataType.Password)] 
    [Display(Name = "New password")] 
    public string NewPassword { get; set; } 

任何人都可以告訴我怎麼去的價值。

Regards

回答

2

屬性需要一個恆定值,所以你需要硬代碼它在你的StringLength屬性中。或者,您可以某處聲明它作爲一個公共不變,可能對你ApplicationUserManager

public class ApplicationUserManager : UserManager<ApplicationUser> 
{ 
    public const int PasswordLength = 8; 

    public ApplicationUserManager() : base(new UserStore<ApplicationUser>(new DataContext())) 
    { 
     PasswordValidator = new MinimumLengthValidator(ApplicationUserManager.PasswordLength); 
    } 
} 

然後,在您的視圖模型,你可以參考相同的恆定

[Required] 
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = ApplicationUserManager.PasswordLength)] 
[DataType(DataType.Password)] 
[Display(Name = "New password")] 
public string NewPassword { get; set; } 

UserManager<T>類有一個公共PasswordValidator屬性,您可以使用它來訪問驗證器。問題是這個屬性是IIdentityValidator<string>,所以它可以使用不同類型的驗證器。您需要將此屬性轉換爲MinimumLengthValidator才能訪問該驗證程序的屬性。你需要類似這樣的代碼:

int requiredLength = 0; 
ApplicationUserManager manager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); 
var validator = manager.PasswordValidator as MinimumLengthValidator; 
if (validator != null) 
{ 
    requiredLength = validator.RequiredLength; 
} 
+0

謝謝斯科特,這對我的問題很有用。只是好奇心,你知道是否有可能獲得MinimunLenghtValidator屬性的值嗎? – RLB

+0

@RLB:我更新了答案,以顯示如何獲得您想要的價值。你只是無法從'StringLength'屬性中完成。 –

0

您可以從成員資格類中獲取屬性。

作爲例子:

// System.Web.Security.Membership 
Membership.MinRequiredPasswordLength 

你也可以改變你的web.config中的值,這是我的:

<membership defaultProvider="DefaultMembershipProvider"> 
    <providers> 
    <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" /> 
    </providers> 
</membership> 
<!--<membership>