且构网

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

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

更新时间:2023-02-16 22:58:17

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

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

  • ValidationAttribute 子类化的自定义属性.当您想将自定义业务逻辑应用到具有属性的特定模型property 时,这很有用.
  • 实施 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.