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

ASP.NET Web API如何优雅修改Model绑定验证的属性名称格式

解决ASP.NET Web API绑定验证错误中属性名称带$符号的问题

针对System.Text.Json序列化下,模型绑定返回的验证错误键带有$.前缀(如$.items[0].price)的问题,推荐通过自定义ProblemDetailsFactory的方式优雅修改格式,无需全局字符串替换。

实现步骤

1. 自定义ProblemDetailsFactory

创建一个继承自ProblemDetailsFactory的类,重写验证错误响应的生成逻辑,调整错误键的格式:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Collections.Generic;

public class CustomProblemDetailsFactory : ProblemDetailsFactory
{
    private readonly ApiBehaviorOptions _apiBehaviorOptions;

    public CustomProblemDetailsFactory(ApiBehaviorOptions apiBehaviorOptions)
    {
        _apiBehaviorOptions = apiBehaviorOptions;
    }

    public override ProblemDetails CreateValidationProblemDetails(
        HttpContext httpContext,
        ModelStateDictionary modelStateDictionary,
        int statusCode = StatusCodes.Status400BadRequest,
        string title = null,
        string type = null,
        string detail = null,
        string instance = null)
    {
        // 生成默认的验证错误响应
        var problemDetails = base.CreateValidationProblemDetails(
            httpContext, modelStateDictionary, statusCode, title, type, detail, instance);

        // 修正错误键:移除开头的`$.`前缀
        if (problemDetails.Errors != null)
        {
            var adjustedErrors = new Dictionary<string, string[]>();
            foreach (var errorEntry in problemDetails.Errors)
            {
                var cleanedKey = errorEntry.Key.StartsWith("$.") 
                    ? errorEntry.Key.Substring(2) 
                    : errorEntry.Key;
                adjustedErrors[cleanedKey] = errorEntry.Value;
            }
            problemDetails.Errors = adjustedErrors;
        }

        return problemDetails;
    }
}

2. 注册自定义工厂

在Program.cs中替换默认的ProblemDetailsFactory实现:

builder.Services.AddSingleton<ProblemDetailsFactory, CustomProblemDetailsFactory>();

效果说明

完成上述配置后,当发送无效JSON触发绑定验证错误时,返回的错误键会自动移除$.前缀,比如items[0].price,而非原始的$.items[0].price。这种方式利用ASP.NET Core的原生扩展点实现,逻辑清晰且符合框架设计规范,避免了生硬的字符串替换操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 15:52:33