简体   繁体   English

用于客户端和服务器端验证的 ASP.NET Core 重用代码

[英]ASP.NET Core Reuse Code for Client-Side and Server-Side Validation

I have a project on ASP.NET Core using Razor pages.我在 ASP.NET Core 上有一个使用 Razor 页面的项目。 I am using Entity Framework but with my own custom entity configuration like below:我正在使用实体框架,但使用我自己的自定义实体配置,如下所示:

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");
      }
   }
}

This allows my entity classes to be free of any form of annotations (leaving them to be just POCOs).这允许我的实体类没有任何形式的注释(让它们只是 POCO)。

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;
      }
   }
}

I am using FluentValidations for validating user input.我正在使用FluentValidations来验证用户输入。 I created custom validator classes.我创建了自定义验证器类。 On the client-side, I have enabled integration of FluentValidation with ASP.NET Core.在客户端,我启用了FluentValidation与 ASP.NET Core 的集成。 On the server-side, I validate manually by invoking the FluentValidation APIs.在服务器端,我通过调用FluentValidation API 手动验证。

Question - Is this approach right?问题 - 这种方法正确吗? Is there any other approach where-in I can re-use the validations on both client and server?有没有其他方法可以在客户端和服务器上重复使用验证? Any pointers or references appreciated.任何指针或参考表示赞赏。

Thanks.谢谢。

At a high level this sounds pretty similar to how I use it at the moment.在高层次上,这听起来与我目前的使用方式非常相似。 There is nothing wrong with doing both client and server side validation, sometimes it's necessary depending on the complexity/dependencies of the rule.进行客户端和服务器端验证没有任何问题,有时根据规则的复杂性/依赖性而有必要。

Some of the tricks that can lead to validator/rule reuse:一些可能导致验证器/规则重用的技巧:

  • Rules that are common can be extracted to property validators or separated into functional concerns , can help with reuse/maintainability常见的规则可以提取到属性验证器或分离为功能关注点,可以帮助重用/可维护性

  • Include(validator) can allow you to sort of mirror your POCO inheritance graph, meaning you can reuse rules from parent class validators Include(validator)可以让你对你的 POCO 继承图进行排序,这意味着你可以重用来自父类验证器的规则

  • Consider implementing client side/server side rule sets to allow you to avoid double handling/invoking the same rules client-side and server-side, or to allow for your services to handle different validation scenarios (eg, the validation strategy may be different for a web app and a separate headless service that both use the same service layer)考虑实施客户端/服务器端规则集,以避免重复处理/调用客户端和服务器端相同的规则,或允许您的服务处理不同的验证场景(例如,验证策略可能不同一个 Web 应用程序和一个单独的无头服务,它们都使用相同的服务层)

  • Set up a custom language manager to override default messages to avoid overuse of the WithMessage extension设置自定义语言管理器来覆盖默认消息,以避免过度使用WithMessage扩展

In terms of user experience I try to funnel as much through to the client side as possible.在用户体验方面,我尝试尽可能多地引导到客户端。 Sometimes this means writing your own client side adapters.有时这意味着编写您自己的客户端适配器。 This is a good start if you need to go down that route.如果您需要沿着这条路线走下去, 是一个好的开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 ASP.NET Core 3.1 MVC 中进行RequiredIf 客户端和服务器端验证? - How to make RequiredIf Client-side and server-side validation in ASP.NET Core 3.1 MVC? ASP.NET客户端与服务器端验证 - ASP.NET Client-side vs Server-side Validation ASP.NET:客户端验证,服务器端操作 - ASP.NET: Client-side validation, server-side action 结合 Asp.Net Core 服务器端和 React 客户端 - Combining Asp.Net Core server-side and React client-side 自定义客户端验证未在 ASP.NET 内核中触发 - Custom Client-Side Validation not triggering in ASP.NET Core 我可以通过ASP.NET将客户端javascript中的对象发送到服务器端代码吗? - Can I send an object from client-side javascript to server-side code via ASP.NET? 从服务器端asp.net注册客户端json的有效方法? - Efficient way to register client-side json from server-side asp.net? 如何在ASP.NET中从客户端调用服务器端函数? - How to call server-side function from client-side in ASP.NET? 客户端(jquery)和服务器端(asp.net)应用程序都可以访问的服务 - Service that can be accessed by both client-side (jquery) and server-side (asp.net) applications Asp.Net:在服务器端还原DropDownList的客户端SelectedItem - Asp.Net: Restoring client-side SelectedItem of DropDownList on server-side
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM