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

.NET8隔离式Azure Function无法为Swagger输出启用帕斯卡命名法

解决.NET8隔离式Azure Function OpenAPI生成Swagger时的帕斯卡命名问题

问题背景

我在.NET8隔离式HTTP触发Azure Function中集成了OpenAPI,使用的是Microsoft.Azure.Functions.Worker.Extensions.OpenApi 1.5.1版本。HostBuilder配置如下:

var host = new HostBuilder()
    //.ConfigureFunctionsWorkerDefaults()
    .ConfigureFunctionsWorkerDefaults(worker => worker.UseNewtonsoftJson())    
    .ConfigureOpenApi()
    .ConfigureServices(services =>
    {
        services.Configure<JsonSerializerOptions>(options =>
        {
            options.PropertyNamingPolicy = null;
            options.Converters.Add(new JsonStringEnumConverter());
        });
        services.AddApplicationInsightsTelemetryWorkerService();
        services.ConfigureFunctionsApplicationInsights();
        services.AddOptions<AzureFunctionAppSettings>().Configure<IConfiguration>((settings, config) =>
        {
            config.Bind(settings);
        });
    })
    .Build();

但生成的Swagger HTML中,所有类和属性名称仍为驼峰命名法,修改全局JsonSerializerOptions并未生效,请问如何让Swagger生成帕斯卡命名的类和属性?

解决方案

问题核心在于:你配置的JsonSerializerOptions是针对函数运行时的System.Text.Json序列化,而OpenApi扩展在调用UseNewtonsoftJson()后,会使用Newtonsoft.Json的独立配置生成Swagger文档,因此全局的System.Text.Json设置不会影响Swagger的命名格式。

需要直接配置OpenApi扩展使用的Newtonsoft.Json序列化规则,具体修改如下:

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults(worker => worker.UseNewtonsoftJson())    
    // 配置OpenApi的序列化设置,启用帕斯卡命名
    .ConfigureOpenApi(options =>
    {
        // 使用DefaultContractResolver保持原始的帕斯卡命名(而非默认驼峰)
        options.SerializerSettings.ContractResolver = new DefaultContractResolver();
        // 可选:添加枚举转字符串的转换器
        options.SerializerSettings.Converters.Add(new StringEnumConverter());
    })
    .ConfigureServices(services =>
    {
        // 此配置仅影响函数运行时的System.Text.Json序列化,与Swagger生成无关
        services.Configure<JsonSerializerOptions>(options =>
        {
            options.PropertyNamingPolicy = null;
            options.Converters.Add(new JsonStringEnumConverter());
        });
        services.AddApplicationInsightsTelemetryWorkerService();
        services.ConfigureFunctionsApplicationInsights();
        services.AddOptions<AzureFunctionAppSettings>().Configure<IConfiguration>((settings, config) =>
        {
            config.Bind(settings);
        });
    })
    .Build();

关键说明

  • DefaultContractResolver是Newtonsoft.Json的默认解析器,它会保留类和属性的原始命名(即代码中的帕斯卡格式),而非自动转换为驼峰。
  • 若未调用UseNewtonsoftJson(),使用默认的System.Text.Json,则需要在ConfigureOpenApi中配置SystemTextJsonSerializerSettings:
    .ConfigureOpenApi(options =>
    {
        options.SystemTextJsonSerializerSettings.PropertyNamingPolicy = null;
        options.SystemTextJsonSerializerSettings.Converters.Add(new JsonStringEnumConverter());
    })
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 01:27:30