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

.NET Core C#中如何从数据注解验证结果获取JsonProperty名称

解决方案

要把ValidationResult中的属性名替换为JsonProperty指定的驼峰命名,核心是通过反射读取属性上的JsonPropertyAttribute,将原属性名映射为JSON字段名。以下是具体实现步骤:

1. 编写属性名映射工具方法

先实现一个静态方法,用来获取指定属性对应的JSON字段名:

public static string GetJsonPropertyName(Type modelType, string propertyName)
{
    var property = modelType.GetProperty(propertyName);
    if (property == null) return propertyName;

    var jsonPropertyAttr = property.GetCustomAttribute<JsonPropertyAttribute>();
    return jsonPropertyAttr?.PropertyName ?? propertyName;
}

这个方法会通过反射定位属性,读取JsonProperty特性的PropertyName值;如果属性未标注该特性,则返回原属性名。

2. 改造验证逻辑,替换属性名

假设你原有的自定义验证扩展类结构如下,只需在验证完成后添加属性名替换逻辑:

public static class ValidationExtensions
{
    public static IEnumerable<ValidationResult> Validate(this object model)
    {
        var validationContext = new ValidationContext(model);
        var results = new List<ValidationResult>();
        Validator.TryValidateObject(model, validationContext, results, validateAllProperties: true);
        
        // 将原属性名替换为JSON字段名
        var modelType = model.GetType();
        return results.Select(result => 
        {
            var jsonMemberNames = result.MemberNames.Select(name => GetJsonPropertyName(modelType, name));
            return new ValidationResult(result.ErrorMessage, jsonMemberNames);
        });
    }
}

3. 实际使用示例

你的UserDetails类定义:

public class UserDetails
{
    [JsonProperty("firstName")]
    [Required(ErrorMessage = "名字不能为空")]
    public string FirstName { get; set; }

    // 其他字段...
}

验证时调用扩展方法,拿到的ValidationResult里的MemberNames就是firstName,直接赋值给自定义异常的targetField即可:

var user = new UserDetails();
var validationResults = user.Validate();
foreach (var result in validationResults)
{
    var customException = new CustomValidationException
    {
        TargetField = result.MemberNames.FirstOrDefault(),
        Message = result.ErrorMessage
    };
    // 抛出或处理异常...
}

补充说明

如果你的项目使用System.Text.Json而非Newtonsoft.Json,只需将JsonPropertyAttribute替换为JsonPropertyNameAttribute,同步修改反射获取的特性类型:

var jsonPropertyAttr = property.GetCustomAttribute<JsonPropertyNameAttribute>();
return jsonPropertyAttr?.Name ?? propertyName;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 17:17:05