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
相关产品推荐
相关产品推荐

