You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core Web Api中FluentValidation验证JObject属性的语法问题

问题原因

  1. MustBeSafeJson()、MaximumLength()都是针对字符串类型设计的FluentValidation验证扩展方法,你直接对JObject类型的MyCustomField属性调用,自然不会出现在智能提示中。
  2. 你之前将ToString()/ToSerializedString()写在RuleFor()的属性选择表达式里,FluentValidation无法解析这种方法调用表达式得到对应的属性名,因此报错信息中的字段标识为空,出现'' cannot contain certain symbol characters.的错误。

正确写法

使用FluentValidation内置的Transform方法,先将JObject属性转换为序列化后的字符串,再应用后续验证规则即可,该写法会保留原属性的绑定关系,错误信息也能正常关联到MyCustomField字段:

public class MyClassValidator : AbstractValidator<MyClass>
{
    public MyClassValidator()
    {
        RuleFor(x => x.Id).NotEmpty();
        
        // MyCustomField验证规则
        RuleFor(x => x.MyCustomField)
            .NotNull() // 如果允许该字段为null可删除此行
            .Transform(field => field.ToSerializedString())
            .MaximumLength(500)
            .MustBeSafeJson();
    }
}

补充说明

如果你的MustBeSafeJson()是自定义扩展方法,确保它是针对string类型实现的验证扩展,即可在Transform之后正常调用。

内容的提问来源于stack exchange,提问作者coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 06:24:04