or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-nswag

The Swagger/OpenAPI API toolchain for .NET and TypeScript distributed as an NPM package

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/nswag@14.2.x

To install, run

npx @tessl/cli install tessl/npm-nswag@14.2.0

index.mddocs/

NSwag

NSwag is a comprehensive OpenAPI/Swagger toolchain for .NET, ASP.NET Core, and TypeScript. The npm package provides command-line tools for .NET and .NET Core distributed as an NPM package, allowing developers to integrate NSwag's powerful OpenAPI specification generation and client code generation capabilities into their JavaScript/TypeScript build processes.

Package Information

  • Package Name: nswag
  • Package Type: npm
  • Language: Node.js CLI wrapper for .NET binaries
  • Installation: npm install nswag (local) or npm install nswag -g (global)

Core Imports

The package provides a CLI binary:

nswag <command> [options]

For global installation:

npm install nswag -g
nswag help

For project installation:

npm install nswag --save-dev
"node_modules/.bin/nswag" help

Basic Usage

# Show available commands
nswag help

# Show version information
nswag version

# Generate TypeScript client from OpenAPI spec
nswag openapi2tsclient /input:api.json /output:client.ts

# Generate C# client from OpenAPI spec
nswag openapi2csclient /input:api.json /output:Client.cs

# Create new NSwag configuration file
nswag new

# Execute NSwag configuration
nswag run config.nswag

System Requirements

  • Node.js: npm >= 3.10.8
  • .NET Runtime: One of the following must be installed on the system:
    • Full .NET Framework 4.6.2+ (Windows only) - Supports x86 and x64 modes
    • .NET 8.0+ (Cross-platform) - Default runtime selection
    • .NET 9.0+ (Cross-platform) - Latest supported version
  • Platform Support:
    • Windows: Full .NET Framework (preferred) or .NET Core/.NET 8.0+
    • Linux/macOS: .NET 8.0+ or .NET 9.0+ required
  • Dependencies: The CLI automatically detects and selects the appropriate runtime

Architecture

NSwag npm package is structured as:

  • CLI Wrapper: Node.js script (bin/nswag.js) that spawns .NET executables
  • Runtime Detection: Automatically detects and selects appropriate .NET runtime
  • .NET Binaries: Contains compiled NSwag binaries for different runtimes
  • Command Registration: Exposes all NSwag .NET commands through the CLI

Capabilities

Version Information

Shows the toolchain version information for both NSwag and NJsonSchema.

nswag version [/runtime:Runtime]

Help Information

Shows help information for all commands or a specific command.

nswag help [command]

Usage Examples:

# Show general help with all available commands
nswag help

# Show detailed help for a specific command
nswag help openapi2tsclient
nswag help openapi2csclient

OpenAPI to TypeScript Client Generation

Generates TypeScript client code from OpenAPI/Swagger specifications with support for multiple client templates.

nswag openapi2tsclient /input:InputFile /output:OutputFile [options]

Basic Configuration:

  • /ClassName:ClassName - The class name of the generated client
  • /ModuleName:ModuleName - The TypeScript module name (default: '', no module)
  • /Namespace:Namespace - The TypeScript namespace (default: '', no namespace)
  • /TypeScriptVersion:Version - The target TypeScript version (default: 2.7)

Template Configuration:

  • /Template:Template - Client template (JQueryCallbacks, JQueryPromises, AngularJS, Angular, Fetch, Aurelia, Axios)
  • /PromiseType:PromiseType - Promise type (Promise or QPromise)
  • /HttpClass:HttpClass - Angular HTTP service class (Http or HttpClient, default: Http)
  • /WithCredentials:Boolean - Send withCredentials in Angular HttpClient requests (default: false)
  • /UseSingletonProvider:Boolean - Use Angular 6 Singleton Provider (default: false)
  • /InjectionTokenType:TokenType - Angular injection token type (InjectionToken or OpaqueToken)
  • /RxJsVersion:Version - Target RxJs version (default: 6.0)

Type Configuration:

  • /DateTimeType:Type - Date time type (Date, MomentJS, Luxon, DayJS, OffsetMomentJS, string)
  • /NullValue:NullValue - Null value in object initializers (Undefined or Null)
  • /TypeStyle:TypeStyle - Type style (default: Class)
  • /EnumStyle:EnumStyle - Enum style (Enum or StringLiteral, default: Enum)
  • /UseLeafType:Boolean - Generate leaf types for discriminator objects (default: false)

Generation Options:

  • /GenerateClientClasses:Boolean - Generate client classes (default: true)
  • /GenerateClientInterfaces:Boolean - Generate interfaces for client classes (default: false)
  • /GenerateOptionalParameters:Boolean - Generate optional parameters (default: false)
  • /ExportTypes:Boolean - Add export keyword to classes/interfaces/enums (default: true)
  • /GenerateDtoTypes:Boolean - Generate DTO classes (default: true)
  • /GenerateResponseClasses:Boolean - Generate response classes (default: true)

Exception Handling:

  • /WrapDtoExceptions:Boolean - Wrap DTO exceptions (default: false)
  • /ExceptionClass:ClassName - The exception class name (default: 'ApiException')

Advanced Features:

  • /ClientBaseClass:ClassName - Base class for generated clients
  • /ConfigurationClass:ClassName - Configuration class name
  • /WrapResponses:Boolean - Wrap success responses for full access
  • /WrapResponseMethods:Methods - Methods where responses are wrapped (comma separated)
  • /ResponseClass:ClassName - Response class name (default: 'SwaggerResponse')
  • /ProtectedMethods:Methods - Methods with protected access modifier (comma separated)
  • /UseTransformOptionsMethod:Boolean - Call transformOptions method (default: false)
  • /UseTransformResultMethod:Boolean - Call transformResult method (default: false)
  • /OperationGenerationMode:Mode - Operation generation mode (SingleClientFromOperationId or MultipleClientsFromPathSegments)
  • /MarkOptionalProperties:Boolean - Mark optional properties with ? (default: false)
  • /GenerateCloneMethod:Boolean - Generate clone() method in DTOs (default: false)
  • /ClassTypes:Types - Type names that generate plain TypeScript classes (comma separated)
  • /ExtendedClasses:Classes - List of extended classes (comma separated)
  • /ExtensionCode:Code - Extension code (string or file path)
  • /GenerateDefaultValues:Boolean - Generate default property values (default: true)
  • /ExcludedTypeNames:Types - Excluded DTO type names (comma separated)
  • /ExcludedParameterNames:Parameters - Globally excluded parameter names (comma separated)
  • /HandleReferences:Boolean - Handle JSON references (default: false)
  • /GenerateTypeCheckFunctions:Boolean - Generate type check functions (Interface style only)
  • /GenerateConstructorInterface:Boolean - Generate constructor interface (Class style only)
  • /ConvertConstructorInterfaceData:Boolean - Convert POJO to DTO instances in constructor
  • /ImportRequiredTypes:Boolean - Import required types (default: true)
  • /UseGetBaseUrlMethod:Boolean - Use getBaseUrl method from base class (default: false)
  • /BaseUrlTokenName:TokenName - Token name for API base URL injection (default: 'API_BASE_URL')
  • /QueryNullValue:Value - Null value for query parameters (default: '')
  • /UseAbortSignal:Boolean - Use AbortSignal (Aurelia/Axios/Fetch only, default: false)
  • /InlineNamedDictionaries:Boolean - Inline named dictionaries (default: false)
  • /InlineNamedAny:Boolean - Inline named any types (default: false)
  • /IncludeHttpContext:Boolean - Include httpContext (Angular only, default: false)

Usage Examples:

# Basic TypeScript client generation
nswag openapi2tsclient /input:petstore.json /output:petstore-client.ts

# Angular client with specific settings
nswag openapi2tsclient /input:api.json /output:api.client.ts /Template:Angular /HttpClass:HttpClient /ClassName:ApiClient

# Fetch-based client with module
nswag openapi2tsclient /input:api.json /output:client.ts /Template:Fetch /ModuleName:ApiClient

OpenAPI to C# Client Generation

Generates C# client code from OpenAPI/Swagger specifications.

nswag openapi2csclient /input:InputFile /output:OutputFile [options]

Basic Configuration:

  • /ClassName:ClassName - Class name of the generated client
  • /ClientBaseClass:BaseClass - Client base class (empty for no base class)
  • /ConfigurationClass:ConfigClass - Configuration class (ClientBaseClass must be set)
  • /GenerateClientClasses:Boolean - Generate client classes (default: true)
  • /GenerateClientInterfaces:Boolean - Generate interfaces for client classes (default: false)
  • /ClientBaseInterface:Interface - Base interface for client interfaces
  • /InjectHttpClient:Boolean - Inject HttpClient instance (default: true)
  • /DisposeHttpClient:Boolean - Dispose HttpClient (injected HttpClient never disposed, default: true)

Exception Handling:

  • /GenerateExceptionClasses:Boolean - Generate exception classes (default: true)
  • /ExceptionClass:ClassName - Exception class name (default: 'SwaggerException')
  • /WrapDtoExceptions:Boolean - Wrap DTO exceptions in SwaggerException (default: true)

HTTP Configuration:

  • /UseHttpClientCreationMethod:Boolean - Call CreateHttpClientAsync on base class
  • /HttpClientType:Type - HttpClient type (default: 'System.Net.Http.HttpClient')
  • /UseHttpRequestMessageCreationMethod:Boolean - Call CreateHttpRequestMessageAsync
  • /UseBaseUrl:Boolean - Use and expose base URL (default: true)
  • /GenerateBaseUrlProperty:Boolean - Generate BaseUrl property (default: true)

Method Generation:

  • /GenerateSyncMethods:Boolean - Generate synchronous methods (default: false)
  • /GeneratePrepareRequestAndProcessResponseAsAsyncMethods:Boolean - Generate async prepare/process methods
  • /ExposeJsonSerializerSettings:Boolean - Expose JsonSerializerSettings property
  • /GenerateUpdateJsonSerializerSettingsMethod:Boolean - Generate UpdateJsonSerializerSettings method

Code Style:

  • /ClientClassAccessModifier:Modifier - Client class access modifier (default: public)
  • /TypeAccessModifier:Modifier - DTO class/enum access modifier (default: public)
  • /PropertySetterAccessModifier:Modifier - Property setter access modifier
  • /GenerateNativeRecords:Boolean - Generate C# 9.0 record types (default: false)
  • /UseRequiredKeyword:Boolean - Use C# 11 'required' keyword (default: false)

Contracts Output:

  • /GenerateContractsOutput:Boolean - Generate separate contracts file
  • /ContractsNamespace:Namespace - Contracts .NET namespace
  • /ContractsOutput:FilePath - Contracts output file path

Parameter Formatting:

  • /ParameterDateTimeFormat:Format - DateTime parameter format (default: 's')
  • /ParameterDateFormat:Format - Date parameter format (default: 'yyyy-MM-dd')
  • /QueryNullValue:Value - Null value for query parameters (default: '')

Advanced Options:

  • /OperationGenerationMode:Mode - Operation generation mode (SingleClientFromOperationId or MultipleClientsFromPathSegments)
  • /AdditionalNamespaceUsages:Namespaces - Additional namespace usages (comma separated)
  • /AdditionalContractNamespaceUsages:Namespaces - Additional contract namespace usages (comma separated)
  • /GenerateOptionalParameters:Boolean - Generate optional parameters (default: false)
  • /GenerateJsonMethods:Boolean - Generate ToJson()/FromJson() methods (default: true)
  • /EnforceFlagEnums:Boolean - Always generate enums as bit flags (default: false)
  • /SerializeTypeInformation:Boolean - Serialize type information in $type property
  • /UseRequestAndResponseSerializationSettings:Boolean - Different request/response serialization settings
  • /ProtectedMethods:Methods - Methods with protected access modifier (comma separated)
  • /SuppressClientClassesOutput:Boolean - Suppress client classes output
  • /SuppressClientInterfacesOutput:Boolean - Suppress client interfaces output

Usage Examples:

# Basic C# client generation
nswag openapi2csclient /input:petstore.json /output:PetstoreClient.cs

# Custom namespace and class name
nswag openapi2csclient /input:api.json /output:Client.cs /Namespace:MyApp.Clients /ClassName:ApiClient

# Generate with interfaces and modern C# features
nswag openapi2csclient /input:api.json /output:Client.cs /GenerateClientInterfaces:true /GenerateNativeRecords:true /UseRequiredKeyword:true

# Generate separate contracts file
nswag openapi2csclient /input:api.json /output:Client.cs /GenerateContractsOutput:true /ContractsOutput:Contracts.cs /ContractsNamespace:MyApp.Contracts

OpenAPI to C# Controller Generation

Generates C# Web API controller code from OpenAPI/Swagger specifications for contract-first development.

nswag openapi2cscontroller /input:InputFile /output:OutputFile [options]

Configuration Options:

  • /ClassName:ClassName - Generated controller class name
  • /ControllerBaseClass:BaseClass - Controller base class (empty for 'ApiController')
  • /ControllerStyle:Style - Controller generation style (partial or abstract, default: partial)
  • /ControllerTarget:Target - Controller target framework (default: AspNetCore)
  • /UseCancellationToken:Boolean - Add cancellation token parameter (default: false)
  • /UseActionResultType:Boolean - Use ASP.NET Core ActionResult type (default: false)
  • /GenerateModelValidationAttributes:Boolean - Add model validation attributes (default: false)
  • /RouteNamingStrategy:Strategy - Route naming strategy (none or operationid, default: none)
  • /BasePath:Path - Base path for the API relative to host

Usage Examples:

# Generate controllers from OpenAPI spec
nswag openapi2cscontroller /input:api.json /output:Controllers.cs

# Generate with custom namespace and ASP.NET Core features
nswag openapi2cscontroller /input:api.json /output:Controllers.cs /Namespace:MyApp.Controllers /UseActionResultType:true /UseCancellationToken:true

# Generate abstract controllers with validation attributes
nswag openapi2cscontroller /input:api.json /output:Controllers.cs /ControllerStyle:abstract /GenerateModelValidationAttributes:true

ASP.NET Core to OpenAPI Generation

Generates OpenAPI/Swagger specifications from ASP.NET Core applications using ApiExplorer.

nswag aspnetcore2openapi /Project:ProjectFile /output:OutputFile [options]

Project Configuration:

  • /Project:ProjectFile - The project file to use (.csproj)
  • /DocumentName:Name - Document name in SwaggerDocumentProvider (default: v1)
  • /MSBuildProjectExtensionsPath:Path - MSBuild project extensions path (default: "obj")
  • /Configuration:Config - Configuration to use (Debug, Release, etc.)
  • /Runtime:Runtime - Runtime to use (e.g., net8.0)
  • /TargetFramework:Framework - Target framework to use
  • /NoBuild:Boolean - Don't build project (use when build is up-to-date)
  • /MSBuildOutputPath:Path - MSBuild output path
  • /Verbose:Boolean - Print verbose output (default: true)
  • /WorkingDirectory:Directory - Working directory to use
  • /AspNetCoreEnvironment:Environment - Set ASPNETCORE_ENVIRONMENT variable

Usage Examples:

# Generate OpenAPI from ASP.NET Core project  
nswag aspnetcore2openapi /Project:MyApi.csproj /output:api.json

# Generate with specific configuration and environment
nswag aspnetcore2openapi /Project:MyApi.csproj /output:swagger.json /Configuration:Release /AspNetCoreEnvironment:Production

# Generate without building (when up-to-date)
nswag aspnetcore2openapi /Project:MyApi.csproj /output:api.json /NoBuild:true

# Generate for specific target framework
nswag aspnetcore2openapi /Project:MyApi.csproj /output:api.json /TargetFramework:net8.0

JSON Schema to TypeScript Generation

Generates TypeScript interfaces from JSON Schema.

nswag jsonschema2tsclient /input:InputFile /output:OutputFile /Name:TypeName [options]

Required Parameters:

  • /Name:TypeName - Type name of the root schema

Configuration Options:

  • /Namespace:Namespace - TypeScript namespace (default: '', no namespace)
  • /TypeScriptVersion:Version - Target TypeScript version (default: 2.7)
  • /DateTimeType:Type - Date time type (Date, MomentJS, Luxon, DayJS, OffsetMomentJS, string)
  • /NullValue:NullValue - Null value in object initializers (Undefined or Null)
  • /GenerateConstructorInterface:Boolean - Generate constructor interface (default: true)
  • /TypeStyle:TypeStyle - Type style (Class or Interface, default: Interface)
  • /EnumStyle:EnumStyle - Enum style (Enum or StringLiteral, default: Enum)
  • /ExportTypes:Boolean - Add export keyword to types (default: true)
  • /MarkOptionalProperties:Boolean - Mark optional properties with ? (default: false)

Usage Examples:

# Generate TypeScript interfaces from JSON Schema
nswag jsonschema2tsclient /input:schema.json /output:types.ts /Name:MySchema

# Generate with custom namespace and type configuration
nswag jsonschema2tsclient /input:schema.json /output:types.ts /Name:ApiTypes /Namespace:MyApp.Types /TypeStyle:Class

# Generate with modern TypeScript features
nswag jsonschema2tsclient /input:schema.json /output:types.ts /Name:Schema /TypeScriptVersion:5.0 /MarkOptionalProperties:true

JSON Schema to C# Generation

Generates C# classes from JSON Schema.

nswag jsonschema2csclient /input:InputFile /output:OutputFile /Name:ClassName /Namespace:Namespace [options]

Required Parameters:

  • /Name:ClassName - Class name of the root schema
  • /Namespace:Namespace - Namespace of generated classes

Type Configuration:

  • /RequiredPropertiesMustBeDefined:Boolean - Required properties must be in JSON (default: true)
  • /DateType:Type - Date .NET type (default: 'DateTimeOffset')
  • /DateTimeType:Type - DateTime .NET type (default: 'DateTimeOffset')
  • /TimeType:Type - Time .NET type (default: 'TimeSpan')
  • /TimeSpanType:Type - TimeSpan .NET type (default: 'TimeSpan')
  • /AnyType:Type - Any .NET type (default: 'object')
  • /ArrayType:Type - Generic array .NET type (default: 'ICollection')
  • /ArrayInstanceType:Type - Generic array .NET instance type (default: 'Collection')
  • /JsonConverters:Converters - Custom Json.NET converter types (comma separated)

Code Generation:

  • /GenerateNativeRecords:Boolean - Generate C# 9.0 record types (default: false)
  • /UseRequiredKeyword:Boolean - Use C# 11 'required' keyword (default: false)
  • /ClassStyle:Style - Class style (Poco, Record, default: Poco)
  • /GenerateDataAnnotations:Boolean - Generate System.ComponentModel.DataAnnotations attributes
  • /GenerateJsonMethods:Boolean - Generate ToJson()/FromJson() methods (default: true)
  • /GenerateDefaultValues:Boolean - Generate default property values (default: true)

Usage Examples:

# Generate C# classes from JSON Schema
nswag jsonschema2csclient /input:schema.json /output:Models.cs /Name:RootModel /Namespace:MyApp.Models

# Generate with modern C# features and data annotations
nswag jsonschema2csclient /input:schema.json /output:Models.cs /Name:ApiModel /Namespace:MyApp.Models /GenerateNativeRecords:true /GenerateDataAnnotations:true

# Generate with custom types and converters
nswag jsonschema2csclient /input:schema.json /output:Models.cs /Name:Model /Namespace:MyApp /DateTimeType:DateTime /ArrayType:List /JsonConverters:MyConverter

Configuration File Management

Creates and executes NSwag configuration files.

# Create new configuration file
nswag new

# Execute configuration file
nswag run [configFile.nswag]

Usage Examples:

# Create new nswag.json configuration in current directory
nswag new

# Execute specific configuration file
nswag run api-config.nswag

# Execute all .nswag files in current directory (if no input specified)
nswag run

Runtime Selection

All commands support runtime selection to control which .NET runtime executes the command.

nswag <command> [options] [/runtime:Runtime]

Runtime Options:

  • /runtime:WinX86 - Full .NET Framework x86 mode (Windows only)
  • /runtime:NetCore - Auto-detect latest supported .NET Core version
  • /runtime:Net80 - .NET 8.0 runtime (default)
  • /runtime:Net90 - .NET 9.0 runtime

Legacy Options (deprecated):

  • --x86 - Equivalent to /runtime:WinX86
  • --core - Equivalent to /runtime:Net80

Usage Examples:

# Use specific .NET runtime
nswag version /runtime:Net90

# Use .NET Core auto-detection
nswag openapi2tsclient /input:api.json /output:client.ts /runtime:NetCore

# Legacy syntax (still supported)
nswag version --core

Common Parameters

Most commands support these common parameters:

Input/Output Parameters

  • /input:FilePath - Input file path (OpenAPI spec, JSON schema, assembly, etc.) or URL
  • /output:FilePath - Output file path for generated code (optional, defaults to console output)
  • /newLineBehavior:Behavior - New line behavior (Auto, CRLF, LF)

Service Configuration Parameters

  • /serviceHost:Host - Overrides the service host of the web document (use '.' to remove hostname)
  • /serviceSchemes:Schemes - Overrides allowed schemes (comma separated: 'http', 'https', 'ws', 'wss')

Runtime Parameters

  • /runtime:Runtime - .NET runtime to use for execution

Error Handling

The CLI wrapper provides:

  • Runtime detection and validation
  • Clear error messages for missing .NET installations
  • Exit code propagation from underlying .NET commands
  • Validation of runtime parameters and command syntax

Commands exit with status code 0 on success or non-zero on failure, making them suitable for CI/CD integration.

Configuration Files

NSwag supports JSON configuration files (.nswag) for complex code generation scenarios. These files allow you to define multiple code generators and their settings in a single configuration.

Configuration File Structure

{
  "runtime": "Net80",
  "defaultVariables": null,
  "documentGenerator": {
    "fromDocument": {
      "url": "https://api.example.com/swagger.json",
      "output": null,
      "newLineBehavior": "Auto"
    }
  },
  "codeGenerators": {
    "openApiToCSharpClient": {
      "clientBaseClass": null,
      "configurationClass": null,
      "generateClientClasses": true,
      "generateClientInterfaces": false,
      "clientBaseInterface": null,
      "injectHttpClient": true,
      "disposeHttpClient": true,
      "protectedMethods": [],
      "generateExceptionClasses": true,
      "exceptionClass": "ApiException",
      "wrapDtoExceptions": true,
      "useHttpClientCreationMethod": false,
      "httpClientType": "System.Net.Http.HttpClient",
      "useHttpRequestMessageCreationMethod": false,
      "useBaseUrl": true,
      "generateBaseUrlProperty": true,
      "generateSyncMethods": false,
      "generatePrepareRequestAndProcessResponseAsAsyncMethods": false,
      "exposeJsonSerializerSettings": false,
      "clientClassAccessModifier": "public",
      "typeAccessModifier": "public",
      "generateContractsOutput": false,
      "contractsNamespace": null,
      "contractsOutputFilePath": null,
      "parameterDateTimeFormat": "s",
      "parameterDateFormat": "yyyy-MM-dd",
      "generateUpdateJsonSerializerSettingsMethod": true,
      "useRequestAndResponseSerializationSettings": false,
      "serializeTypeInformation": false,
      "queryNullValue": "",
      "className": "{controller}Client",
      "operationGenerationMode": "SingleClientFromOperationId",
      "additionalNamespaceUsages": [],
      "additionalContractNamespaceUsages": [],
      "generateOptionalParameters": false,
      "generateJsonMethods": true,
      "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": true,
      "responseClass": "SwaggerResponse",
      "namespace": "MyNamespace",
      "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": false,
      "excludedTypeNames": [],
      "excludedParameterNames": [],
      "handleReferences": false,
      "generateImmutableArrayProperties": false,
      "generateImmutableDictionaryProperties": false,
      "jsonSerializerSettingsTransformationMethod": null,
      "inlineNamedArrays": false,
      "inlineNamedDictionaries": false,
      "inlineNamedTuples": true,
      "inlineNamedAny": false,
      "generateDtoTypes": true,
      "generateOptionalPropertiesAsNullable": false,
      "generateNullableReferenceTypes": false,
      "templateDirectory": null,
      "typeNameGeneratorType": null,
      "propertyNameGeneratorType": null,
      "enumNameGeneratorType": null,
      "serviceHost": null,
      "serviceSchemes": null,
      "output": "Generated/ApiClient.cs"
    },
    "openApiToTypeScriptClient": {
      "className": "{controller}Client",
      "moduleName": "",
      "namespace": "",
      "typeScriptVersion": 2.7,
      "template": "Angular",
      "promiseType": "Promise",
      "httpClass": "HttpClient",
      "withCredentials": false,
      "useSingletonProvider": false,
      "injectionTokenType": "InjectionToken",
      "rxJsVersion": 6.0,
      "dateTimeType": "Date",
      "nullValue": "Undefined",
      "generateClientClasses": true,
      "generateClientInterfaces": false,
      "generateOptionalParameters": false,
      "exportTypes": true,
      "wrapDtoExceptions": false,
      "exceptionClass": "ApiException",
      "clientBaseClass": null,
      "wrapResponses": false,
      "wrapResponseMethods": [],
      "generateResponseClasses": true,
      "responseClass": "SwaggerResponse",
      "protectedMethods": [],
      "configurationClass": null,
      "useTransformOptionsMethod": false,
      "useTransformResultMethod": false,
      "generateDtoTypes": true,
      "operationGenerationMode": "SingleClientFromOperationId",
      "markOptionalProperties": false,
      "generateCloneMethod": false,
      "typeStyle": "Class",
      "enumStyle": "Enum",
      "useLeafType": false,
      "classTypes": [],
      "extendedClasses": [],
      "extensionCode": null,
      "generateDefaultValues": true,
      "excludedTypeNames": [],
      "excludedParameterNames": [],
      "handleReferences": false,
      "generateTypeCheckFunctions": false,
      "generateConstructorInterface": true,
      "convertConstructorInterfaceData": false,
      "importRequiredTypes": true,
      "useGetBaseUrlMethod": false,
      "baseUrlTokenName": "API_BASE_URL",
      "queryNullValue": "",
      "useAbortSignal": false,
      "inlineNamedDictionaries": false,
      "inlineNamedAny": false,
      "includeHttpContext": false,
      "templateDirectory": null,
      "typeNameGeneratorType": null,
      "propertyNameGeneratorType": null,
      "enumNameGeneratorType": null,
      "serviceHost": null,
      "serviceSchemes": null,
      "output": "Generated/api-client.ts"
    }
  }
}

Using Configuration Files

# Create a new configuration file with default settings
nswag new

# Execute a specific configuration file
nswag run myproject.nswag

# Execute all .nswag files in current directory
nswag run

# Execute with variables
nswag run /Variables:"baseUrl=https://api.example.com,version=v2"

Troubleshooting

Common Issues and Solutions

Error: "Could not detect .NET Core version"

  • Ensure .NET 8.0+ or .NET 9.0+ is installed on your system
  • Verify installation with: dotnet --version
  • On Linux/macOS, install .NET runtime: sudo apt-get install dotnet-runtime-8.0

Error: "Unsupported /runtime: argument"

  • Check available runtime options: WinX86, NetCore, Net80, Net90
  • Use /runtime:NetCore for automatic detection of latest installed version
  • Verify .NET installation matches the specified runtime

Error: "The full .NET Framework installation not found"

  • This occurs on Windows when trying to use /runtime:WinX86 without full .NET Framework
  • Install .NET Framework 4.6.2+ or use .NET 8.0+ runtime instead
  • Use /runtime:Net80 for cross-platform compatibility

Error: "Multiple /runtime: arguments detected"*

  • Remove legacy --core or --x86 arguments when using /runtime: parameter
  • Use only one runtime specification per command

Error: "Input file not found" or network errors

  • Verify input file path or URL is accessible
  • For URLs, ensure network connectivity and valid OpenAPI/Swagger endpoint
  • Check file permissions for local files

Performance Issues with Large Specifications

  • Use /output:filename to write to file instead of console output
  • Consider breaking large specifications into smaller, focused schemas
  • Increase available memory if generating large client libraries

Generated Code Compilation Errors

  • Verify target framework compatibility between generated code and your project
  • Check for missing NuGet package dependencies in generated clients
  • Review namespace conflicts in generated code

Getting Help

For additional help with specific commands:

nswag help [command]

For community support and detailed documentation:

  • NSwag Wiki
  • GitHub Issues
  • Command Line Documentation