使用自定义惟一属性扩展UserValidator
本文关键字:属性 扩展 UserValidator 自定义 | 更新日期: 2023-09-27 18:03:57
我想在Asp.net Identity 2.0中扩展UserValidator或类似的东西,不仅可以检查唯一的电子邮件,还可以检查我选择的唯一值。下面是我想用别名做的例子。这是可能的,还是我必须写一张支票到处我可以更新别名?
public class ApplicationUserManager : UserManager<ApplicationUser, int>
{
public ApplicationUserManager(IUserStore<ApplicationUser, int> store)
: base(store)
{
this.UserValidator = new UserValidator<ApplicationUser, int>(this)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
//This does not exist
//RequireUniqueAlias = true
};
}
}
public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole,
CustomUserClaim>
{
[Required]
public string Alias { get; set; }
}
有点棘手,但可能,需要一个自定义UserValidator。看着Microsoft.AspNet.Identity.Core源码真的帮了我大忙。
https://aspnetidentity.codeplex.com/SourceControl/latest src/Microsoft.AspNet.Identity.Core UserValidator.cs
CustomUserValidator,删除了一些由于正文字符限制的注释:
public class CustomUserValidator<TUser> : UserValidator<TUser, int>
where TUser : ApplicationUser
{
public bool RequireUniqueAlias { get; set; }
public CustomUserValidator(UserManager<TUser, int> manager) : base(manager)
{
this.Manager = manager;
}
private UserManager<TUser, int> Manager { get; set; }
public override async Task<IdentityResult> ValidateAsync(TUser item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
var errors = new List<string>();
await ValidateUserName(item, errors);
if (RequireUniqueEmail)
{
await ValidateEmail(item, errors);
}
if (RequireUniqueAlias)
{
await ValidateAlias(item, errors);
}
if (errors.Count > 0)
{
return IdentityResult.Failed(errors.ToArray());
}
return IdentityResult.Success;
}
private async Task ValidateUserName(TUser user, List<string> errors)
{
if (string.IsNullOrWhiteSpace(user.UserName))
{
errors.Add(String.Format(CultureInfo.CurrentCulture, CustomResources.PropertyTooShort, "Name"));
}
else if (AllowOnlyAlphanumericUserNames && !Regex.IsMatch(user.UserName, @"^[A-Za-z0-9@_'.]+$"))
{
// If any characters are not letters or digits, its an illegal user name
errors.Add(String.Format(CultureInfo.CurrentCulture, CustomResources.InvalidUserName, user.UserName));
}
else
{
var owner = await Manager.FindByNameAsync(user.UserName);
if (owner != null && !EqualityComparer<int>.Default.Equals(owner.Id, user.Id))
{
errors.Add(String.Format(CultureInfo.CurrentCulture, CustomResources.DuplicateName, user.UserName));
}
}
}
// make sure email is not empty, valid, and unique
private async Task ValidateEmail(TUser user, List<string> errors)
{
if (!user.Email.IsNullOrWhiteSpace())
{
if (string.IsNullOrWhiteSpace(user.Email))
{
errors.Add(String.Format(CultureInfo.CurrentCulture, CustomResources.PropertyTooShort, "Email"));
return;
}
try
{
var m = new MailAddress(user.Email);
}
catch (FormatException)
{
errors.Add(String.Format(CultureInfo.CurrentCulture, CustomResources.InvalidEmail, user.Email));
return;
}
}
var owner = await Manager.FindByEmailAsync(user.Email);
if (owner != null && !EqualityComparer<int>.Default.Equals(owner.Id, user.Id))
{
errors.Add(String.Format(CultureInfo.CurrentCulture, CustomResources.DuplicateEmail, user.Email));
}
}
private async Task ValidateAlias(TUser user, List<string> errors)
{
if (!user.Alias.IsNullOrWhiteSpace())
{
if (string.IsNullOrWhiteSpace(user.Alias))
{
errors.Add(String.Format(CultureInfo.CurrentCulture, CustomResources.PropertyTooShort, "Alias"));
return;
}
}
var owner = Manager.Users.FirstOrDefault(x => x.Alias == user.Alias);
if (owner != null && !EqualityComparer<int>.Default.Equals(owner.Id, user.Id))
{
errors.Add(String.Format(CultureInfo.CurrentCulture, CustomResources.DuplicateAlias, user.Alias));
}
}
}
除了小的修改,你还需要添加一个自定义资源文件,这是非常有用的,如果你想自定义Asp.net Identity 2.0用户名已经采取验证消息或其他消息。添加一个资源文件,例如CustomResources.resx。在文件资源管理器中打开文件夹并编辑CustomResource。Resx在记事本或类似的。替换为以下数据:
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="DefaultError" xml:space="preserve">
<value>An unknown failure has occured.</value>
<comment>Default identity result error message</comment>
</data>
<data name="DuplicateEmail" xml:space="preserve">
<value>Email '{0}' is already taken.</value>
<comment>error for duplicate emails</comment>
</data>
<data name="DuplicateName" xml:space="preserve">
<value>Name {0} is already taken.</value>
<comment>error for duplicate usernames</comment>
</data>
<data name="ExternalLoginExists" xml:space="preserve">
<value>A user with that external login already exists.</value>
<comment>Error when a login already linked</comment>
</data>
<data name="InvalidEmail" xml:space="preserve">
<value>Email '{0}' is invalid.</value>
<comment>invalid email</comment>
</data>
<data name="InvalidToken" xml:space="preserve">
<value>Invalid token.</value>
<comment>Error when a token is not recognized</comment>
</data>
<data name="InvalidUserName" xml:space="preserve">
<value>User name {0} is invalid, can only contain letters or digits.</value>
<comment>usernames can only contain letters or digits</comment>
</data>
<data name="LockoutNotEnabled" xml:space="preserve">
<value>Lockout is not enabled for this user.</value>
<comment>error when lockout is not enabled</comment>
</data>
<data name="NoTokenProvider" xml:space="preserve">
<value>No IUserTokenProvider is registered.</value>
<comment>Error when there is no IUserTokenProvider</comment>
</data>
<data name="NoTwoFactorProvider" xml:space="preserve">
<value>No IUserTwoFactorProvider for '{0}' is registered.</value>
<comment>Error when there is no provider found</comment>
</data>
<data name="PasswordMismatch" xml:space="preserve">
<value>Incorrect password.</value>
<comment>Error when a password doesn't match</comment>
</data>
<data name="PasswordRequireDigit" xml:space="preserve">
<value>Passwords must have at least one digit ('0'-'9').</value>
<comment>Error when passwords do not have a digit</comment>
</data>
<data name="PasswordRequireLower" xml:space="preserve">
<value>Passwords must have at least one lowercase ('a'-'z').</value>
<comment>Error when passwords do not have a lowercase letter</comment>
</data>
<data name="PasswordRequireNonLetterOrDigit" xml:space="preserve">
<value>Passwords must have at least one non letter or digit character.</value>
<comment>Error when password does not have enough letter or digit characters</comment>
</data>
<data name="PasswordRequireUpper" xml:space="preserve">
<value>Passwords must have at least one uppercase ('A'-'Z').</value>
<comment>Error when passwords do not have an uppercase letter</comment>
</data>
<data name="PasswordTooShort" xml:space="preserve">
<value>Passwords must be at least {0} characters.</value>
<comment>Error message for passwords that are too short</comment>
</data>
<data name="PropertyTooShort" xml:space="preserve">
<value>{0} cannot be null or empty.</value>
<comment>error for empty or null usernames</comment>
</data>
<data name="RoleNotFound" xml:space="preserve">
<value>Role {0} does not exist.</value>
<comment>error when a role does not exist</comment>
</data>
<data name="StoreNotIQueryableRoleStore" xml:space="preserve">
<value>Store does not implement IQueryableRoleStore<TRole>.</value>
<comment>error when the store does not implement this interface</comment>
</data>
<data name="StoreNotIQueryableUserStore" xml:space="preserve">
<value>Store does not implement IQueryableUserStore<TUser>.</value>
<comment>error when the store does not implement this interface</comment>
</data>
<data name="StoreNotIUserClaimStore" xml:space="preserve">
<value>Store does not implement IUserClaimStore<TUser>.</value>
<comment>error when the store does not implement this interface</comment>
</data>
<data name="StoreNotIUserConfirmationStore" xml:space="preserve">
<value>Store does not implement IUserConfirmationStore<TUser>.</value>
<comment>error when the store does not implement this interface</comment>
</data>
<data name="StoreNotIUserEmailStore" xml:space="preserve">
<value>Store does not implement IUserEmailStore<TUser>.</value>
<comment>error when the store does not implement this interface</comment>
</data>
<data name="StoreNotIUserLockoutStore" xml:space="preserve">
<value>Store does not implement IUserLockoutStore<TUser>.</value>
<comment>error when the store does not implement this interface</comment>
</data>
<data name="StoreNotIUserLoginStore" xml:space="preserve">
<value>Store does not implement IUserLoginStore<TUser>.</value>
<comment>error when the store does not implement this interface</comment>
</data>
<data name="StoreNotIUserPasswordStore" xml:space="preserve">
<value>Store does not implement IUserPasswordStore<TUser>.</value>
<comment>error when the store does not implement this interface</comment>
</data>
<data name="StoreNotIUserPhoneNumberStore" xml:space="preserve">
<value>Store does not implement IUserPhoneNumberStore<TUser>.</value>
<comment>error when the store does not implement this interface</comment>
</data>
<data name="StoreNotIUserRoleStore" xml:space="preserve">
<value>Store does not implement IUserRoleStore<TUser>.</value>
<comment>error when the store does not implement this interface</comment>
</data>
<data name="StoreNotIUserSecurityStampStore" xml:space="preserve">
<value>Store does not implement IUserSecurityStampStore<TUser>.</value>
<comment>error when the store does not implement this interface</comment>
</data>
<data name="StoreNotIUserTwoFactorStore" xml:space="preserve">
<value>Store does not implement IUserTwoFactorStore<TUser>.</value>
<comment>error when the store does not implement this interface</comment>
</data>
<data name="UserAlreadyHasPassword" xml:space="preserve">
<value>User already has a password set.</value>
<comment>error when AddPassword called when a user already has a password</comment>
</data>
<data name="UserAlreadyInRole" xml:space="preserve">
<value>User already in role.</value>
<comment>Error when a user is already in a role</comment>
</data>
<data name="UserIdNotFound" xml:space="preserve">
<value>UserId not found.</value>
<comment>No user with this id found</comment>
</data>
<data name="UserNameNotFound" xml:space="preserve">
<value>User {0} does not exist.</value>
<comment>error when a user does not exist</comment>
</data>
<data name="UserNotInRole" xml:space="preserve">
<value>User is not in role.</value>
<comment>Error when a user is not in the role</comment>
</data>
</root>
CustomResources开放。resx和添加您的属性,在我的情况下"DuplicateAlias"作为名称。现在打开CustomResource。在internal static global::System.Globalization.CultureInfo Culture
/// <summary>
/// Looks up a localized string similar to An unknown failure has occured..
/// </summary>
internal static string DefaultError {
get {
return ResourceManager.GetString("DefaultError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Email '{0}' is already taken..
/// </summary>
internal static string DuplicateEmail {
get {
return ResourceManager.GetString("DuplicateEmail", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Name {0} is already taken..
/// </summary>
internal static string DuplicateName {
get {
return ResourceManager.GetString("DuplicateName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Alias {0} is already taken..
/// </summary>
internal static string DuplicateAlias {
get {
return ResourceManager.GetString("DuplicateAlias", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A user with that external login already exists..
/// </summary>
internal static string ExternalLoginExists {
get {
return ResourceManager.GetString("ExternalLoginExists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Email '{0}' is invalid..
/// </summary>
internal static string InvalidEmail {
get {
return ResourceManager.GetString("InvalidEmail", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid token..
/// </summary>
internal static string InvalidToken {
get {
return ResourceManager.GetString("InvalidToken", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User name {0} is invalid, can only contain letters or digits..
/// </summary>
internal static string InvalidUserName {
get {
return ResourceManager.GetString("InvalidUserName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Lockout is not enabled for this user..
/// </summary>
internal static string LockoutNotEnabled {
get {
return ResourceManager.GetString("LockoutNotEnabled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No IUserTokenProvider is registered..
/// </summary>
internal static string NoTokenProvider {
get {
return ResourceManager.GetString("NoTokenProvider", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No IUserTwoFactorProvider for '{0}' is registered..
/// </summary>
internal static string NoTwoFactorProvider {
get {
return ResourceManager.GetString("NoTwoFactorProvider", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Incorrect password..
/// </summary>
internal static string PasswordMismatch {
get {
return ResourceManager.GetString("PasswordMismatch", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Passwords must have at least one digit ('0'-'9')..
/// </summary>
internal static string PasswordRequireDigit {
get {
return ResourceManager.GetString("PasswordRequireDigit", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Passwords must have at least one lowercase ('a'-'z')..
/// </summary>
internal static string PasswordRequireLower {
get {
return ResourceManager.GetString("PasswordRequireLower", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Passwords must have at least one non letter or digit character..
/// </summary>
internal static string PasswordRequireNonLetterOrDigit {
get {
return ResourceManager.GetString("PasswordRequireNonLetterOrDigit", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Passwords must have at least one uppercase ('A'-'Z')..
/// </summary>
internal static string PasswordRequireUpper {
get {
return ResourceManager.GetString("PasswordRequireUpper", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Passwords must be at least {0} characters..
/// </summary>
internal static string PasswordTooShort {
get {
return ResourceManager.GetString("PasswordTooShort", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} cannot be null or empty..
/// </summary>
internal static string PropertyTooShort {
get {
return ResourceManager.GetString("PropertyTooShort", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Role {0} does not exist..
/// </summary>
internal static string RoleNotFound {
get {
return ResourceManager.GetString("RoleNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IQueryableRoleStore<TRole>..
/// </summary>
internal static string StoreNotIQueryableRoleStore {
get {
return ResourceManager.GetString("StoreNotIQueryableRoleStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IQueryableUserStore<TUser>..
/// </summary>
internal static string StoreNotIQueryableUserStore {
get {
return ResourceManager.GetString("StoreNotIQueryableUserStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserClaimStore<TUser>..
/// </summary>
internal static string StoreNotIUserClaimStore {
get {
return ResourceManager.GetString("StoreNotIUserClaimStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserConfirmationStore<TUser>..
/// </summary>
internal static string StoreNotIUserConfirmationStore {
get {
return ResourceManager.GetString("StoreNotIUserConfirmationStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserEmailStore<TUser>..
/// </summary>
internal static string StoreNotIUserEmailStore {
get {
return ResourceManager.GetString("StoreNotIUserEmailStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserLockoutStore<TUser>..
/// </summary>
internal static string StoreNotIUserLockoutStore {
get {
return ResourceManager.GetString("StoreNotIUserLockoutStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserLoginStore<TUser>..
/// </summary>
internal static string StoreNotIUserLoginStore {
get {
return ResourceManager.GetString("StoreNotIUserLoginStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserPasswordStore<TUser>..
/// </summary>
internal static string StoreNotIUserPasswordStore {
get {
return ResourceManager.GetString("StoreNotIUserPasswordStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserPhoneNumberStore<TUser>..
/// </summary>
internal static string StoreNotIUserPhoneNumberStore {
get {
return ResourceManager.GetString("StoreNotIUserPhoneNumberStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserRoleStore<TUser>..
/// </summary>
internal static string StoreNotIUserRoleStore {
get {
return ResourceManager.GetString("StoreNotIUserRoleStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserSecurityStampStore<TUser>..
/// </summary>
internal static string StoreNotIUserSecurityStampStore {
get {
return ResourceManager.GetString("StoreNotIUserSecurityStampStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store does not implement IUserTwoFactorStore<TUser>..
/// </summary>
internal static string StoreNotIUserTwoFactorStore {
get {
return ResourceManager.GetString("StoreNotIUserTwoFactorStore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User already has a password set..
/// </summary>
internal static string UserAlreadyHasPassword {
get {
return ResourceManager.GetString("UserAlreadyHasPassword", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User already in role..
/// </summary>
internal static string UserAlreadyInRole {
get {
return ResourceManager.GetString("UserAlreadyInRole", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to UserId not found..
/// </summary>
internal static string UserIdNotFound {
get {
return ResourceManager.GetString("UserIdNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User {0} does not exist..
/// </summary>
internal static string UserNameNotFound {
get {
return ResourceManager.GetString("UserNameNotFound", resourceCulture);
}
}