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

.NET 6升级.NET 8后NSwag生成客户端报SelectedSwaggerGeneratorRaw错误

解决.NET 8升级后NSwag生成客户端代码的空引用及代码不生成问题

问题分析

升级到.NET 8并更新NSwag.MSBuild至14.0.4后出现的NullReferenceException,是因为新版本NSwag要求显式指定文档生成器类型,原配置缺少selectedDocumentGenerator字段导致序列化失败;而设置noBuild:false后错误消失但代码不生成,是因为配置中缺少代码生成器的具体规则,NSwag没有明确的输出逻辑。

解决方案

1. 修正NSwag.json配置结构

在配置中添加selectedDocumentGenerator字段,并补充codeGenerators节点定义客户端代码生成规则:

{
  "runtime": "Net80",
  "defaultVariables": "Configuration=Release,OutDir=bin/Release/net8.0/,HomeDir=%USERPROFILE%",
  "selectedDocumentGenerator": "webApiToOpenApi", // 显式指定使用WebApi转OpenApi生成器
  "documentGenerator": {
    "webApiToOpenApi": {
      "controllerNames": [],
      "isAspNetCore": true,
      "resolveJsonOptions": false,
      "defaultUrlTemplate": "api/{controller}/{id?}",
      "addMissingPathParameters": false,
      "includedVersions": null,
      "defaultPropertyNameHandling": "CamelCase",
      "defaultReferenceTypeNullHandling": "Null",
      "defaultDictionaryValueReferenceTypeNullHandling": "NotNull",
      "defaultResponseReferenceTypeNullHandling": "Null",
      "defaultEnumHandling": "Integer",
      "flattenInheritanceHierarchy": false,
      "generateKnownTypes": true,
      "generateEnumMappingDescription": false,
      "generateXmlObjects": false,
      "generateAbstractProperties": false,
      "generateAbstractSchemas": true,
      "ignoreObsoleteProperties": false,
      "allowReferencesWithProperties": false,
      "excludedTypeNames": [],
      "serviceHost": null,
      "serviceBasePath": null,
      "serviceSchemes": [],
      "infoTitle": "User Authentication Content Services",
      "infoDescription": null,
      "infoVersion": "1.0.0",
      "documentTemplate": null,
      "documentProcessorTypes": [],
      "operationProcessorTypes": [],
      "typeNameGeneratorType": null,
      "schemaNameGeneratorType": null,
      "contractResolverType": null,
      "serializerSettingsType": null,
      "useDocumentProvider": true,
      "documentName": "v1",
      "aspNetCoreEnvironment": null,
      "createWebHostBuilderMethod": null,
      "startupType": null,
      "allowNullableBodyParameters": true,
      "output": null,
      "outputType": "Swagger2",
      "newLineBehavior": "Auto",
      "assemblyPaths": [
        "$(OutDir)/AControllers.dll",
        "$(OutDir)/AppServices.dll"
      ],
      "assemblyConfig": null,
      "referencePaths": [
        "$(HomeDir)/.nuget/packages"
      ],
      "useNuGetCache": false
    }
  },
  "codeGenerators": {
    "openApiToCSharpClient": {
      "className": "{controller}Client",
      "namespace": "YourProject.Client", // 替换为你的客户端命名空间
      "output": "GeneratedClients/ApiClient.cs", // 指定代码输出路径
      "generateClientInterfaces": true,
      "generateDtoTypes": true,
      "httpClientType": "System.Net.Http.HttpClient",
      "injectHttpClient": true,
      "useStringEnum": true,
      "jsonLibrary": "NewtonsoftJson", // 若项目用System.Text.Json则改为"SystemTextJson"
      "generateOptionalParameters": true
    }
  }
}

2. 检查并完善MSBuild命令配置

确保项目文件(.csproj)中NSwag的执行目标正确关联到构建流程,示例:

<ItemGroup>
  <PackageReference Include="NSwag.MSBuild" Version="14.1.1" /> <!-- 建议升级到最新稳定版 -->
</ItemGroup>

<Target Name="GenerateApiClients" AfterTargets="Build">
  <Exec Command="$(NSwagExe) run NSwag.json /variables:Configuration=$(Configuration),OutDir=$(OutDir)" />
</Target>

3. 清理重建并验证路径

  • 执行dotnet clean和dotnet build,确保输出目录的dll文件存在且路径正确;
  • 检查$(OutDir)变量是否正确指向bin/{Configuration}/net8.0目录,避免NSwag找不到目标程序集。

4. 升级NSwag到最新稳定版

14.0.4存在部分.NET 8兼容性问题,建议升级到14.x系列的最新稳定版本(如14.1.1),可通过dotnet命令更新:

dotnet add package NSwag.MSBuild --version 14.1.1

内容的提问来源于stack exchange,提问作者R.A 1

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 23:48:12