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

ASP.NET Core WebApi如何全局配置将查询参数转换为snake_case格式

最简全局配置方案

仅需两步即可实现全局查询参数自动转为snake_case格式,无需给每个属性/参数单独加注解:

1. (可选)如果需要处理Action单个camelCase参数的转换,先添加如下短约定类

using Microsoft.AspNetCore.Mvc.ApplicationModels;
using System.Text.Json;

public class SnakeCaseQueryParameterConvention : IActionModelConvention
{
    public void Apply(ActionModel action)
    {
        foreach (var parameter in action.Parameters)
        {
            // 仅处理查询来源的参数
            if (parameter.BindingInfo?.BindingSource == Microsoft.AspNetCore.Mvc.ModelBinding.BindingSource.Query)
            {
                parameter.ParameterName = JsonNamingPolicy.SnakeCaseLower.ConvertName(parameter.ParameterName);
            }
        }
    }
}

2. 全局注册配置

在Startup.ConfigureServices或者.NET 6+的顶层Program.cs中,修改控制器注册逻辑即可:

services.AddControllers(options =>
{
    // 注册参数转换约定
    options.Conventions.Add(new SnakeCaseQueryParameterConvention());
    // 注册PascalCase模型属性的snake_case绑定规则
    options.ModelMetadataDetailsProviders.Add(new SystemTextJsonValidationMetadataProvider(JsonNamingPolicy.SnakeCaseLower));
})
.AddJsonOptions(options =>
{
    // 如果需要接口返回的JSON也用snake_case格式,可以加上这两行,不需要就删除
    options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower;
    options.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.SnakeCaseLower;
});

// 你已有的LowercaseUrls配置保留即可
services.Configure<RouteOptions>(options => options.LowercaseUrls = true);

效果验证

配置完成后,直接支持/weatherforecast?city=Berlin&total_days=3格式的请求,自动绑定到PascalCase的Query.City、Query.TotalDays属性,以及camelCase格式的Action参数,无需额外修改业务代码。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:57:03