禁用特定 DTO 的数据注释

Disable data annotation for specific DTO

提问人:CaglarAyhan 提问时间:10/17/2023 最后编辑:CaglarAyhan 更新时间:10/17/2023 访问量:35

问:

我想在某些情况下禁用数据注释验证。假设我们有两个 DTO 和两个终结点

public class CreateBulkProductDto 
{
        [Required]
        public List<CreateProductDto> Products { get; set; }
 }

public class CreateProductDto {
    [Required]
    [StringLength(100)]
    public string Name { get; set; }
    [Required]
    public List<CreateProductCategoryDto> Categories { get; set; }
    [Required]
    public List<string> Barcodes { get; set; }

}

端点;

public virtual async Task<List<CreateOrUpdateBulkProductResultDto>> CreateBulkAsync(CreateBulkProductDto input){.....}
public virtual async Task<string> CreateAsync(CreateProductDto input){....} 

当请求到达 CreateBulkAsync 时,我想禁用验证,但当请求到达 CreateAsync 时,我希望验证正常工作。我怎样才能解决这个问题

C# .NET 验证 数据批注

评论


答:

1赞 Roe 10/17/2023 #1

我为此编写了一个扩展方法。它目前仅适用于单个键值。但我想你自己可以扩展这一点。

仅当您显式选中 .ModelState.IsValid

If (!ModelState.IsValid) { return; }

请确保不要过度使用它,因为无论如何都不建议跳过验证。

public static bool MarkFieldsValid(this ModelStateDictionary modelState, string key)
{
    if (string.IsNullOrWhitespace(key)) { return false; }
    
    var modelStates = modelState.FindKeysWithPrefix(key);

    foreach (var state in modelStates)
    {
        modelState.ClearValidationState(state.Key);
        modelState.MarkFieldValid(state.Key);
    }

    return true;
}

然后你可以像这样实现它:

ModelState.MarkFieldsValid("key");

If (!ModelState.IsValid) { return; }