Asp.net MVC:无法将类型 'Models.RegisterViewModel' 的对象强制转换为类型 'Models.ApplicationUser'



我目前正在开发一个ASP.NET应用程序,并决定进行自定义验证。我添加了";名称";到我的RegisterViewModel和ApplicationUser模型,这样它们就会有一个名称,并希望验证它是唯一的。我创建了一个名为UniqueName的类,并将其设置为验证属性。问题是validationContext.ObjectInstance的强制转换。当我将其强制转换为ApplicationUser时,我会得到

Unable to cast object of type 'Starset.Models.RegisterViewModel' to type 'Starset.Models.ApplicationUser'.

当我尝试注册时。当我把它投射到RegisterViewModel时,我得到了

Unable to cast object of type 'Starset.Models.ApplicationUser' to type 'Starset.Models.RegisterViewModel'.

我尝试使用AutoMapper来映射两者,但没有成功。为什么它说我的用户对象的类型是RegisterViewModel,然后它的类型是ApplicationUser?哪一个?

public class UniqueName: ValidationAttribute
{
private ApplicationDbContext _context;
public UniqueName()
{
_context = new ApplicationDbContext();
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var allUsers = _context.Users.ToList();
var user = (RegisterViewModel) (validationContext.ObjectInstance);
foreach(var existingUser in allUsers)
{
if(existingUser.Name == user.Name)
{
return new ValidationResult("Username Taken");
}
}
return ValidationResult.Success;
}
}
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[UniqueName]
public string Name { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class ApplicationUser : IdentityUser
{
[Required]
[UniqueName]
public string Name { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}

请帮助我完成自定义验证。

将代码更改为:

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var userName = value.ToString();
var userNameExist = _context.Users.Any(u=>u.Name==userName);
if(userNameExist) return new ValidationResult("Username Taken");
return ValidationResult.Success;
}

相关内容

最新更新