【发布时间】:2021-08-14 05:41:24
【问题描述】:
在 .NET Core 3.x 应用程序中,我有一个类似以下的模型,其中使用了自定义验证属性 [CustomValidator]。为 CustomValidator 返回的错误消息没有 $. 前缀,而内置 JSON 验证器返回前缀。我想让它们保持一致(无论是否始终使用 $. 前缀)。知道如何做到这一点吗?
示例模型:
public class Dto
{
public float Price {get; set;}
[CustomValidator] public int? EntityID {get; set;}
}
[CustomValidator] 是一个自定义验证属性,它执行类似的操作
public class CustomValidatorAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var isValid = CheckSomething(...);
return isValid
? ValidationResult.Success
: new ValidationResult($"Invalid value for Entity");
}
}
我在Controller.Action 中验证模型
if (!ModelState.IsValid) return BadRequest(ModelState);
对于输入:
{
"Price" : "abc"
}
返回
{
...
"errors": {
"$.price": [
"The JSON value could not be converted to System.Single. Path: $.price | LineNumber: 7 | BytePositionInLine: 21."
]
}
}
而对于输入:
{
"Price" : 1.0,
"EntityID": -1,
}
返回
{
...
"errors": {
"EntityID": [
"Invalid value for Entity"
]
}
}
我希望 errors 始终具有一致的属性名称,例如Price 和 EntityID 而不是 $.price 和 EntityID
【问题讨论】:
标签: c# asp.net-core .net-core asp.net-core-mvc asp.net-core-3.1