且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在ASP.NET Core中实现自定义模型验证?

更新时间:2023-02-16 23:02:25

在ASP.NET Core中有两种方法可以进行自定义模型验证:

There are two ways to do custom model validation in ASP.NET Core:

  • ValidationAttribute子类化的自定义属性.当您要将自定义业务逻辑应用于具有属性的特定模型属性时,这很有用.
  • 实施IValidatableObject进行类级验证.如果您需要一次对整个模型进行验证,请改用此方法.
  • A custom attribute subclassed from ValidationAttribute. This is useful when you want to apply custom business logic to a particular model property with an attribute.
  • Implementing IValidatableObject for class-level validation. Use this instead when you need to do validation on an entire model at once.

文档都有这两个例子.在您的情况下,IValidatableObject可能是***的方法.

The documentation has examples of both. In your case, IValidatableObject would probably be the best approach.