Skip to content

.Net 9.0 NSwagExe_Net90 failing to generate C# client #5127

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
chriscameron-vertexinc opened this issue Mar 26, 2025 · 9 comments · Fixed by #5146
Closed

.Net 9.0 NSwagExe_Net90 failing to generate C# client #5127

chriscameron-vertexinc opened this issue Mar 26, 2025 · 9 comments · Fixed by #5146

Comments

@chriscameron-vertexinc
Copy link

Describe the bug

Hello! Thank you for the excellent project!

Since upgrading my test project (previously working for .Net 7 and .Net 8) to .Net 9 I'm now getting the following error when generating my C# client via post-build step:

  <Target Name="NSwag" AfterTargets="Build">
    <Exec Command="$(NSwagExe_Net90) run nswag.json /variables:Configuration=$(Configuration)" />
  </Target>
  CNR.Example.API net9.0 failed with 1 error(s) (7.6s) → CNR.Example.API\bin\Debug\net9.0\CNR.Example.API.dll
    NSwag command line tool for .NET Core Net90, toolchain v14.2.0.0 (NJsonSchema v11.1.0.0 (Newtonsoft.Json v13.0.0.0))
    Visit http://NSwag.org for more information.
    NSwag bin directory: C:\Users\Christopher.Cameron\.nuget\packages\nswag.msbuild\14.2.0\tools\Net90

    Executing file 'nswag.json' with variables 'Configuration=Debug'...
    System.ArgumentException: The path is empty. (Parameter 'path')
       at System.IO.Path.GetFullPath(String path)
       at NSwag.Commands.Generation.AspNetCore.ProjectMetadata.GetProjectMetadata(String file, String buildExtensionsDir, String framework, String configuration, String runtime, Boolean noBuild, String outputPath, IConsoleHost console) in /_/src/NSwag.Commands/Commands/Generation/AspNetCore/ProjectMetadata.cs:line 113
       at NSwag.Commands.Generation.AspNetCore.AspNetCoreToOpenApiCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in /_/src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiCommand.cs:line 70
       at NSwag.Commands.NSwagDocumentBase.GenerateSwaggerDocumentAsync() in /_/src/NSwag.Commands/NSwagDocumentBase.cs:line 270
       at NSwag.Commands.NSwagDocument.ExecuteAsync() in /_/src/NSwag.Commands/NSwagDocument.cs:line 67
       at NSwag.Commands.Document.ExecuteDocumentCommand.ExecuteDocumentAsync(IConsoleHost host, String filePath) in /_/src/NSwag.Commands/Commands/Document/ExecuteDocumentCommand.cs:line 76
       at NSwag.Commands.Document.ExecuteDocumentCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in /_/src/NSwag.Commands/Commands/Document/ExecuteDocumentCommand.cs:line 33
       at NConsole.CommandLineProcessor.ProcessSingleAsync(String[] args, Object input)
       at NConsole.CommandLineProcessor.ProcessAsync(String[] args, Object input)
       at NSwag.Commands.NSwagCommandProcessor.ProcessAsync(String[] args) in /_/src/NSwag.Commands/NSwagCommandProcessor.cs:line 65
    C:\Workspace\cnr-common-asp-2\src\CNR.Example.API\CNR.Example.API.csproj(36,5): error MSB3073: The command "dotnet "C:\Users\Christopher.Cameron\.nuget\packages\nswag.msbuild\14.2.0\buildTransitive\../tools/Net90/dotnet-nswag.dll" run nswag.json /variables:Configuration=Debug" exited with code -1.

Build failed with 1 error(s) and 8 warning(s) in 10.7s

Version of NSwag toolchain, computer and .NET runtime used

NSwag command line tool for .NET Core Net90, toolchain v14.2.0.0 (NJsonSchema v11.1.0.0 (Newtonsoft.Json v13.0.0.0))

To Reproduce

Here's my nswag.json configuration:

{
  "runtime": "Net90",
  "defaultVariables": null,
  "documentGenerator": {
    "aspNetCoreToOpenApi": {
      "project": "CNR.Example.API.csproj",
      "msBuildProjectExtensionsPath": null,
      "configuration": "$(Configuration)",
      "runtime": null,
      "targetFramework": null,
      "noBuild": true,
      "msBuildOutputPath": null,
      "verbose": true,
      "workingDirectory": null,
      "requireParametersWithoutDefault": false,
      "apiGroupNames": null,
      "defaultPropertyNameHandling": "Default",
      "defaultReferenceTypeNullHandling": "Null",
      "defaultDictionaryValueReferenceTypeNullHandling": "NotNull",
      "defaultResponseReferenceTypeNullHandling": "NotNull",
      "generateOriginalParameterNames": true,
      "defaultEnumHandling": "Integer",
      "flattenInheritanceHierarchy": false,
      "generateKnownTypes": true,
      "generateEnumMappingDescription": false,
      "generateXmlObjects": false,
      "generateAbstractProperties": false,
      "generateAbstractSchemas": true,
      "ignoreObsoleteProperties": false,
      "allowReferencesWithProperties": false,
      "useXmlDocumentation": true,
      "resolveExternalXmlDocumentation": true,
      "excludedTypeNames": [],
      "serviceHost": ".",
      "serviceBasePath": null,
      "serviceSchemes": [],
      "infoTitle": "My Title",
      "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,
      "useHttpAttributeNameAsOperationId": false,
      "output": null,
      "outputType": "Swagger2",
      "newLineBehavior": "Auto",
      "assemblyPaths": [],
      "assemblyConfig": null,
      "referencePaths": [],
      "useNuGetCache": false
    }
  },
  "codeGenerators": {
    "openApiToCSharpClient": {
      "clientBaseClass": "AbstractNSwagClient",
      "configurationClass": "INSwagClientDependencies",
      "generateClientClasses": true,
      "generateClientInterfaces": true,
      "clientBaseInterface": "INSwagClient",
      "injectHttpClient": true,
      "disposeHttpClient": true,
      "protectedMethods": [],
      "generateExceptionClasses": false,
      "exceptionClass": "ApiClientException",
      "wrapDtoExceptions": true,
      "useHttpClientCreationMethod": false,
      "httpClientType": "System.Net.Http.HttpClient",
      "useHttpRequestMessageCreationMethod": false,
      "useBaseUrl": false,
      "generateBaseUrlProperty": false,
      "generateSyncMethods": false,
      "generatePrepareRequestAndProcessResponseAsAsyncMethods": true,
      "exposeJsonSerializerSettings": false,
      "clientClassAccessModifier": "public",
      "typeAccessModifier": "public",
      "generateContractsOutput": false,
      "contractsNamespace": null,
      "contractsOutputFilePath": null,
      "parameterDateTimeFormat": "s",
      "parameterDateFormat": "yyyy-MM-dd",
      "generateUpdateJsonSerializerSettingsMethod": false,
      "useRequestAndResponseSerializationSettings": false,
      "serializeTypeInformation": false,
      "queryNullValue": "",
      "className": "{controller}Client",
      "operationGenerationMode": "MultipleClientsFromOperationId",
      "additionalNamespaceUsages": [
        "CNR.Common.ASP.Collections",
        "CNR.Common.ASP.Exceptions",
        "CNR.Common.ASP.NSwag",
        "CNR.Example.Model",
        "Microsoft.AspNetCore.JsonPatch.Operations"
      ],
      "additionalContractNamespaceUsages": [],
      "generateOptionalParameters": true,
      "generateJsonMethods": false,
      "enforceFlagEnums": false,
      "parameterArrayType": "System.Collections.Generic.IEnumerable",
      "parameterDictionaryType": "System.Collections.Generic.IDictionary",
      "responseArrayType": "System.Collections.Generic.ICollection",
      "responseDictionaryType": "System.Collections.Generic.IDictionary",
      "wrapResponses": false,
      "wrapResponseMethods": [],
      "generateResponseClasses": false,
      "responseClass": "SwaggerResponse",
      "namespace": "CNR.Example.Client",
      "requiredPropertiesMustBeDefined": true,
      "dateType": "System.DateTimeOffset",
      "jsonConverters": null,
      "anyType": "object",
      "dateTimeType": "System.DateTimeOffset",
      "timeType": "System.TimeSpan",
      "timeSpanType": "System.TimeSpan",
      "arrayType": "System.Collections.Generic.ICollection",
      "arrayInstanceType": "System.Collections.ObjectModel.Collection",
      "dictionaryType": "System.Collections.Generic.IDictionary",
      "dictionaryInstanceType": "System.Collections.Generic.Dictionary",
      "arrayBaseType": "System.Collections.ObjectModel.Collection",
      "dictionaryBaseType": "System.Collections.Generic.Dictionary",
      "classStyle": "Poco",
      "jsonLibrary": "NewtonsoftJson",
      "generateDefaultValues": true,
      "generateDataAnnotations": true,
      "excludedTypeNames": [],
      "excludedParameterNames": [ "X-Correlation-ID" ],
      "handleReferences": false,
      "generateImmutableArrayProperties": false,
      "generateImmutableDictionaryProperties": false,
      "jsonSerializerSettingsTransformationMethod": null,
      "inlineNamedArrays": false,
      "inlineNamedDictionaries": false,
      "inlineNamedTuples": true,
      "inlineNamedAny": false,
      "generateDtoTypes": false,
      "generateOptionalPropertiesAsNullable": false,
      "generateNullableReferenceTypes": true,
      "templateDirectory": null,
      "typeNameGeneratorType": null,
      "propertyNameGeneratorType": null,
      "enumNameGeneratorType": null,
      "serviceHost": ".",
      "serviceSchemes": null,
      "output": "../CNR.Example.Client/ExampleClient.Generated.cs",
      "newLineBehavior": "LF"
    }
  }
}

Expected behavior

C# client is successfully regenerated with minimal changes

Additional context

When we migrated from .Net 7 to .Net 8 we had to make some changes to our nswag.json configuration #4524 (comment)

@hegy-100
Copy link

Any update on this?

@chriscameron-vertexinc
Copy link
Author

Nothing from my end, I'll update the issue if I ever find a resolution

@lahma
Copy link
Collaborator

lahma commented Apr 16, 2025

Try adding WorkingDirectory="$(ProjectDir)" to Exec command and tune build events, like it's recommended in the docs.

@chriscameron-vertexinc
Copy link
Author

No luck with adding WorkingDirectory to the Exec command

@lahma
Copy link
Collaborator

lahma commented Apr 18, 2025

What does this command output (you can remove sensitive full paths if needed, replace csproj with your path.

dotnet msbuild /nologo /verbosity:quiet /p:Configuration=debug C:\path\your.csproj --getProperty:BaseIntermediateOutputPath;Platform;AssemblyName;OutputPath;PlatformTarget;ProjectDepsFilePath;ProjectDir;ProjectRuntimeConfigFilePath;TargetFileName;TargetFrameworkIdentifier

@chriscameron-vertexinc
Copy link
Author

PS C:\Workspace\cnr-common-asp\src\CNR.Example.API> dotnet msbuild /nologo /verbosity:quiet /p:Configuration=debug CNR.Example.API.csproj --getProperty:'BaseIntermediateOutputPath;Platform;AssemblyName;OutputPath;PlatformTarget;ProjectDepsFilePath;ProjectDir;ProjectRuntimeConfigFilePath;TargetFileName;TargetFrameworkIdentifier'
{
  "Properties": {
    "BaseIntermediateOutputPath": "C:\\Workspace\\cnr-common-asp\\src\\CNR.Example.API\\obj\\",
    "Platform": "AnyCPU",
    "AssemblyName": "CNR.Example.API",
    "OutputPath": "bin\\debug\\",
    "PlatformTarget": "",
    "ProjectDepsFilePath": "",
    "ProjectDir": "",
    "ProjectRuntimeConfigFilePath": "",
    "TargetFileName": "",
    "TargetFrameworkIdentifier": ""
  }
}

@lahma
Copy link
Collaborator

lahma commented Apr 18, 2025

These empty values (ProjectDir for example) seem really weird, do you have some kind of special build targets or anything else that could cause this?

@lahma
Copy link
Collaborator

lahma commented Apr 18, 2025

Or multi-level Directory.Build.props?

@lahma
Copy link
Collaborator

lahma commented Apr 20, 2025

You can validate the fix by using https://www.myget.org/F/nswag/api/v3/index.json feed and package version 14.3.1-preview-20250420-0810 or later.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants