C# 用于客户端和服务器端验证的ASP.NET核心重用代码
我在ASP.NET Core上有一个使用Razor页面的项目。我使用的是实体框架,但有自己的自定义实体配置,如下所示:C# 用于客户端和服务器端验证的ASP.NET核心重用代码,c#,entity-framework,validation,asp.net-core,C#,Entity Framework,Validation,Asp.net Core,我在ASP.NET Core上有一个使用Razor页面的项目。我使用的是实体框架,但有自己的自定义实体配置,如下所示: namespace Customer.Data.Relational.Configuration { public sealed class CustomerConfiguration { public static void Configure(EntityTypeBuilder<CustomerEntity> entity) {
namespace Customer.Data.Relational.Configuration {
public sealed class CustomerConfiguration {
public static void Configure(EntityTypeBuilder<CustomerEntity> entity) {
entity.ToTable("customers")
.HasKey(k => k.Id)
.HasName("pk_customers");
entity.Property(p => p.Id)
.HasColumnName("customer_id")
.HasColumnType("bigint")
.ValueGeneratedOnAdd()
.IsRequired();
entity.Property(p => p.Code)
.HasColumnName("customer_code")
.HasColumnType("nvarchar(15)")
.IsRequired();
entity.Property(p => p.FirstName)
.HasColumnName("first_name")
.HasColumnType("nvarchar(100)")
.IsRequired();
entity.Property(p => p.LastName)
.HasColumnName("last_name")
.HasColumnType("nvarchar(100)")
.IsRequired();
entity.Property(p => p.EmailAddress)
.HasColumnName("email_address")
.HasColumnType("nvarchar(100)")
.IsRequired();
entity.Property(p => p.IsPremierCustomer)
.HasColumnName("premier_customer")
.HasColumnType("bit")
.IsRequired();
entity.HasIndex(k => k.Code)
.HasName("uq_customers")
.IsUnique();
entity.HasOne(o => o.CustomerType)
.WithMany()
.HasForeignKey(f => f.CustomerTypeId)
.OnDelete(DeleteBehavior.Restrict)
.HasConstraintName("fk_customers_customer_types");
}
}
}
我正在使用验证用户输入。我创建了自定义验证器类。在客户端,我启用了FluentValidation与ASP.NET Core的集成。在服务器端,我通过调用FluentValidation API手动验证
问题-这种方法正确吗?是否有其他方法可以在客户端和服务器上重复使用验证?如有任何指示或参考,不胜感激
谢谢。在较高的层次上,这听起来与我目前使用它的方式非常相似。同时进行客户端和服务器端验证并没有什么错,有时根据规则的复杂性/依赖性进行验证是必要的 可能导致验证程序/规则重用的一些技巧:
- 通用规则可以提取或分离为,有助于重用/可维护性
可以让您在某种程度上镜像POCO继承图,这意味着您可以重用来自父类验证器的规则Include(validator)
- 考虑实施客户端/服务器端,以避免在客户端和服务器端重复处理/调用相同的规则,或允许您的服务处理不同的验证场景(例如,对于使用相同服务层的web应用程序和单独的headless服务,验证策略可能不同)
- 设置自定义语言管理器以覆盖默认消息,以避免过度使用WithMessage扩展名
namespace Customer.Entities {
public class CustomerEntity : IAuditableEntity {
public long Id { get; set; } = default;
public string Code {
get; set;
}
public string FirstName {
get; set;
}
public string LastName {
get; set;
}
public string EmailAddress {
get; set;
}
public bool IsPremierCustomer {
get; set;
}
}
}