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

NSwag.AspNetCore 14.1版本JsonSerializer驼峰配置及SerializerSettings缺失问题

NSwag 新版本配置驼峰命名(CamelCase)的替代方案

NSwag 新版本重构了配置结构,原 OpenApiDocumentSettings 下的 SerializerSettings 属性已被移除,需通过以下方式配置驼峰命名:

情况1:继续使用 Newtonsoft.Json(Json.NET)

将原配置的 SerializerSettings 迁移到 SchemaSettings.JsonSerializerSettings 节点下,代码修改如下:

private void AddSwaggerEndpoints(IServiceCollection services, UnoSwaggerEndpoint[] endpoints)
{
    var nswagDefaultSerializerSettings = new JsonSerializerSettings()
    {
        ContractResolver = new CamelCasePropertyNamesContractResolver(),
    };

    foreach (var endpoint in endpoints.OrderBy(e => e.DocumentName))
    {
        services.AddOpenApiDocument(o =>
        {
            o.DocumentName = endpoint.DocumentName;
            o.Title = endpoint.Title;
            o.ApiGroupNames = endpoint.ApiGroupName;
            // 替换原 SerializerSettings 配置
            o.SchemaSettings.JsonSerializerSettings = nswagDefaultSerializerSettings;
            o.SchemaSettings.SchemaNameGenerator = new NestedClassNameSchemaNameGenerator();
            o.Version = endpoint.Version;
            o.SchemaSettings.AllowReferencesWithProperties = true;
            o.SchemaSettings.GenerateEnumMappingDescription = true;
            o.DocumentProcessors.Add(new SignalRTypescriptDocumentProcessor(endpoint));
            o.DocumentProcessors.Add(new SchemaSorterDocumentProcessor());
        });
    }
}

情况2:使用 System.Text.Json(推荐现代项目使用)

若项目已迁移至 System.Text.Json,需配置 JsonSerializerOptions 并指定驼峰命名策略:

private void AddSwaggerEndpoints(IServiceCollection services, UnoSwaggerEndpoint[] endpoints)
{
    var camelCaseOptions = new JsonSerializerOptions
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
    };

    foreach (var endpoint in endpoints.OrderBy(e => e.DocumentName))
    {
        services.AddOpenApiDocument(o =>
        {
            o.DocumentName = endpoint.DocumentName;
            o.Title = endpoint.Title;
            o.ApiGroupNames = endpoint.ApiGroupName;
            // 配置 System.Text.Json 序列化设置
            o.SchemaSettings.SystemTextJsonSerializerSettings = camelCaseOptions;
            o.SchemaSettings.SchemaNameGenerator = new NestedClassNameSchemaNameGenerator();
            o.Version = endpoint.Version;
            o.SchemaSettings.AllowReferencesWithProperties = true;
            o.SchemaSettings.GenerateEnumMappingDescription = true;
            o.DocumentProcessors.Add(new SignalRTypescriptDocumentProcessor(endpoint));
            o.DocumentProcessors.Add(new SchemaSorterDocumentProcessor());
        });
    }
}

说明

新版本 NSwag 将序列化配置按 JSON 序列化库类型拆分到了 SchemaSettings 下的对应节点,确保配置更清晰,同时兼容不同的序列化方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 03:15:57