排名
3
文章
317
粉丝
22
评论
14
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256


欢迎加群交流技术

验证DTO
微软官方文档:https://docs.microsoft.com/zh-cn/aspnet/core/mvc/models/validation?view=aspnetcore-7.0
数据注解 Attribute
使用数据注解是一种以声明式对DTO进行验证的简单方法. 示例 :
public class CreateBookDto
{
[Required]
[StringLength(100)]
public string Name { get; set; }
[Required]
[StringLength(1000)]
public string Description { get; set; }
[Range(0, 999.99)]
public decimal Price { get; set; }
}
当使用该类作为应用服务或控制器的参数时,将对其自动验证并抛出本地化异常(由ABP框架处理).
IValidatableObject
IValidatableObject can be implemented by a DTO to perform custom validation logic. CreateBookDto in the following example implements this interface and checks if the Name is equals to the Description and returns a validation error in this case. 可以将DTO实现 IValidatableObject 接口进行自定义验证逻辑. 下面的示例中 CreateBookDto 实现了这个接口,并检查 Name 是否等于 Description 并返回一个验证错误.
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Acme.BookStore
{
public class CreateBookDto : IValidatableObject
{
[Required]
[StringLength(100)]
public string Name { get; set; }
[Required]
[StringLength(1000)]
public string Description { get; set; }
[Range(0, 999.99)]
public decimal Price { get; set; }
public IEnumerable<ValidationResult> Validate(
ValidationContext validationContext)
{
if (Name == Description)
{
yield return new ValidationResult(
"Name and Description can not be the same!",
new[] { "Name", "Description" }
);
}
}
}
}
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739。有需要软件开发,或者学习软件技术的朋友可以和我联系~(Q:815170684)
评价