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

4

本文介绍了如何在 ASP.NET Core 中实现自定义模型验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在以前版本的 ASP.NET MVC 中,向模型添加自定义验证的方法是实现 IValidatableObject 并实现自己的 Validate() 方法.举个例子:

In previous versions of ASP.NET MVC the way to add custom validation to your model was by implementing the IValidatableObject and implementing your own Validate() method. As an example:

public class BestModelEver : IValidatableObject {
    public DateTime? Birthday { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
        if (Birthday.HasValue) {
            yield return new ValidationResult("Error message goes here");
        }
    }
}

这仍然是向 ASP.NET Core 中的模型添加自定义验证的推荐方法吗?使用 IValidatableObject 会产生 System.ComponentModel.DataAnnotations 依赖.

Is this still the recommended way of adding custom validation to a model in ASP.NET Core? Using IValidatableObject takes on a System.ComponentModel.DataAnnotations dependency.

推荐答案

在 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.

这篇关于如何在 ASP.NET Core 中实现自定义模型验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14