ASP.NET Web API 6:使用验证归因于唯一用户名
我在这里没有太多代码 但是,我想为用户名创建自己的验证,而这些用户名不会重复。
模型:
[Table("User")]
public partial class User
{
[Key]
public Guid Id { get; set; } = Guid.NewGuid();
[Column("userName")]
[StringLength(200)]
[AllValidation(ErrorMessage = "foo")]
[Required(ErrorMessage = "Username is a required field")]
public string UserName { get; set; } = null!;
[StringLength(50, MinimumLength = 3, ErrorMessage = "The password should be between 3 characters to 50")]
[Required(ErrorMessage = "Password is a required field")]
public string Password { get; set; } = null!;
//[Column(TypeName = "date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy/MM/dd}")]
public DateTime? LastLogin { get; set; }
public string? Token { get; set; }
}
验证attribute:
public class AllValidationAttribute : ValidationAttribute
{
private readonly TalkBackDbContext _context;
public AllValidationAttribute(TalkBackDbContext context)
{
_context = context;
}
public override string FormatErrorMessage(string name)
{
return _context.Users.SingleOrDefault(x => x.UserName == name)!.ToString()!;
}
}
当我尝试将errormessage插入属性中时,我会遇到错误,
这是错误:
I do not have much code here
But I want to create my own validation for username that will not have duplicates.
Model:
[Table("User")]
public partial class User
{
[Key]
public Guid Id { get; set; } = Guid.NewGuid();
[Column("userName")]
[StringLength(200)]
[AllValidation(ErrorMessage = "foo")]
[Required(ErrorMessage = "Username is a required field")]
public string UserName { get; set; } = null!;
[StringLength(50, MinimumLength = 3, ErrorMessage = "The password should be between 3 characters to 50")]
[Required(ErrorMessage = "Password is a required field")]
public string Password { get; set; } = null!;
//[Column(TypeName = "date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy/MM/dd}")]
public DateTime? LastLogin { get; set; }
public string? Token { get; set; }
}
ValidationAttribute:
public class AllValidationAttribute : ValidationAttribute
{
private readonly TalkBackDbContext _context;
public AllValidationAttribute(TalkBackDbContext context)
{
_context = context;
}
public override string FormatErrorMessage(string name)
{
return _context.Users.SingleOrDefault(x => x.UserName == name)!.ToString()!;
}
}
I get an error when I try to insert ErrorMessage into an attribute
this is the error:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以做到这一点。
将其从构造函数和覆盖iSVALID方法中删除。
you can do this.
remove it from constructor and override IsValid method.