The Swagger/OpenAPI API toolchain for .NET and TypeScript distributed as an NPM package
npx @tessl/cli install tessl/npm-nswag@14.2.00
# NSwag
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: nswag
7
- **Package Type**: npm
8
- **Language**: Node.js CLI wrapper for .NET binaries
9
- **Installation**: `npm install nswag` (local) or `npm install nswag -g` (global)
10
11
## Core Imports
12
13
The package provides a CLI binary:
14
15
```bash
16
nswag <command> [options]
17
```
18
19
For global installation:
20
21
```bash
22
npm install nswag -g
23
nswag help
24
```
25
26
For project installation:
27
28
```bash
29
npm install nswag --save-dev
30
"node_modules/.bin/nswag" help
31
```
32
33
## Basic Usage
34
35
```bash
36
# Show available commands
37
nswag help
38
39
# Show version information
40
nswag version
41
42
# Generate TypeScript client from OpenAPI spec
43
nswag openapi2tsclient /input:api.json /output:client.ts
44
45
# Generate C# client from OpenAPI spec
46
nswag openapi2csclient /input:api.json /output:Client.cs
47
48
# Create new NSwag configuration file
49
nswag new
50
51
# Execute NSwag configuration
52
nswag run config.nswag
53
```
54
55
## System Requirements
56
57
- **Node.js**: npm >= 3.10.8
58
- **.NET Runtime**: One of the following must be installed on the system:
59
- Full .NET Framework 4.6.2+ (Windows only) - Supports x86 and x64 modes
60
- .NET 8.0+ (Cross-platform) - Default runtime selection
61
- .NET 9.0+ (Cross-platform) - Latest supported version
62
- **Platform Support**:
63
- Windows: Full .NET Framework (preferred) or .NET Core/.NET 8.0+
64
- Linux/macOS: .NET 8.0+ or .NET 9.0+ required
65
- **Dependencies**: The CLI automatically detects and selects the appropriate runtime
66
67
## Architecture
68
69
NSwag npm package is structured as:
70
71
- **CLI Wrapper**: Node.js script (`bin/nswag.js`) that spawns .NET executables
72
- **Runtime Detection**: Automatically detects and selects appropriate .NET runtime
73
- **.NET Binaries**: Contains compiled NSwag binaries for different runtimes
74
- **Command Registration**: Exposes all NSwag .NET commands through the CLI
75
76
## Capabilities
77
78
### Version Information
79
80
Shows the toolchain version information for both NSwag and NJsonSchema.
81
82
```bash { .api }
83
nswag version [/runtime:Runtime]
84
```
85
86
### Help Information
87
88
Shows help information for all commands or a specific command.
89
90
```bash { .api }
91
nswag help [command]
92
```
93
94
**Usage Examples:**
95
96
```bash
97
# Show general help with all available commands
98
nswag help
99
100
# Show detailed help for a specific command
101
nswag help openapi2tsclient
102
nswag help openapi2csclient
103
```
104
105
### OpenAPI to TypeScript Client Generation
106
107
Generates TypeScript client code from OpenAPI/Swagger specifications with support for multiple client templates.
108
109
```bash { .api }
110
nswag openapi2tsclient /input:InputFile /output:OutputFile [options]
111
```
112
113
**Basic Configuration:**
114
- `/ClassName:ClassName` - The class name of the generated client
115
- `/ModuleName:ModuleName` - The TypeScript module name (default: '', no module)
116
- `/Namespace:Namespace` - The TypeScript namespace (default: '', no namespace)
117
- `/TypeScriptVersion:Version` - The target TypeScript version (default: 2.7)
118
119
**Template Configuration:**
120
- `/Template:Template` - Client template (JQueryCallbacks, JQueryPromises, AngularJS, Angular, Fetch, Aurelia, Axios)
121
- `/PromiseType:PromiseType` - Promise type (Promise or QPromise)
122
- `/HttpClass:HttpClass` - Angular HTTP service class (Http or HttpClient, default: Http)
123
- `/WithCredentials:Boolean` - Send withCredentials in Angular HttpClient requests (default: false)
124
- `/UseSingletonProvider:Boolean` - Use Angular 6 Singleton Provider (default: false)
125
- `/InjectionTokenType:TokenType` - Angular injection token type (InjectionToken or OpaqueToken)
126
- `/RxJsVersion:Version` - Target RxJs version (default: 6.0)
127
128
**Type Configuration:**
129
- `/DateTimeType:Type` - Date time type (Date, MomentJS, Luxon, DayJS, OffsetMomentJS, string)
130
- `/NullValue:NullValue` - Null value in object initializers (Undefined or Null)
131
- `/TypeStyle:TypeStyle` - Type style (default: Class)
132
- `/EnumStyle:EnumStyle` - Enum style (Enum or StringLiteral, default: Enum)
133
- `/UseLeafType:Boolean` - Generate leaf types for discriminator objects (default: false)
134
135
**Generation Options:**
136
- `/GenerateClientClasses:Boolean` - Generate client classes (default: true)
137
- `/GenerateClientInterfaces:Boolean` - Generate interfaces for client classes (default: false)
138
- `/GenerateOptionalParameters:Boolean` - Generate optional parameters (default: false)
139
- `/ExportTypes:Boolean` - Add export keyword to classes/interfaces/enums (default: true)
140
- `/GenerateDtoTypes:Boolean` - Generate DTO classes (default: true)
141
- `/GenerateResponseClasses:Boolean` - Generate response classes (default: true)
142
143
**Exception Handling:**
144
- `/WrapDtoExceptions:Boolean` - Wrap DTO exceptions (default: false)
145
- `/ExceptionClass:ClassName` - The exception class name (default: 'ApiException')
146
147
**Advanced Features:**
148
- `/ClientBaseClass:ClassName` - Base class for generated clients
149
- `/ConfigurationClass:ClassName` - Configuration class name
150
- `/WrapResponses:Boolean` - Wrap success responses for full access
151
- `/WrapResponseMethods:Methods` - Methods where responses are wrapped (comma separated)
152
- `/ResponseClass:ClassName` - Response class name (default: 'SwaggerResponse')
153
- `/ProtectedMethods:Methods` - Methods with protected access modifier (comma separated)
154
- `/UseTransformOptionsMethod:Boolean` - Call transformOptions method (default: false)
155
- `/UseTransformResultMethod:Boolean` - Call transformResult method (default: false)
156
- `/OperationGenerationMode:Mode` - Operation generation mode (SingleClientFromOperationId or MultipleClientsFromPathSegments)
157
- `/MarkOptionalProperties:Boolean` - Mark optional properties with ? (default: false)
158
- `/GenerateCloneMethod:Boolean` - Generate clone() method in DTOs (default: false)
159
- `/ClassTypes:Types` - Type names that generate plain TypeScript classes (comma separated)
160
- `/ExtendedClasses:Classes` - List of extended classes (comma separated)
161
- `/ExtensionCode:Code` - Extension code (string or file path)
162
- `/GenerateDefaultValues:Boolean` - Generate default property values (default: true)
163
- `/ExcludedTypeNames:Types` - Excluded DTO type names (comma separated)
164
- `/ExcludedParameterNames:Parameters` - Globally excluded parameter names (comma separated)
165
- `/HandleReferences:Boolean` - Handle JSON references (default: false)
166
- `/GenerateTypeCheckFunctions:Boolean` - Generate type check functions (Interface style only)
167
- `/GenerateConstructorInterface:Boolean` - Generate constructor interface (Class style only)
168
- `/ConvertConstructorInterfaceData:Boolean` - Convert POJO to DTO instances in constructor
169
- `/ImportRequiredTypes:Boolean` - Import required types (default: true)
170
- `/UseGetBaseUrlMethod:Boolean` - Use getBaseUrl method from base class (default: false)
171
- `/BaseUrlTokenName:TokenName` - Token name for API base URL injection (default: 'API_BASE_URL')
172
- `/QueryNullValue:Value` - Null value for query parameters (default: '')
173
- `/UseAbortSignal:Boolean` - Use AbortSignal (Aurelia/Axios/Fetch only, default: false)
174
- `/InlineNamedDictionaries:Boolean` - Inline named dictionaries (default: false)
175
- `/InlineNamedAny:Boolean` - Inline named any types (default: false)
176
- `/IncludeHttpContext:Boolean` - Include httpContext (Angular only, default: false)
177
178
**Usage Examples:**
179
180
```bash
181
# Basic TypeScript client generation
182
nswag openapi2tsclient /input:petstore.json /output:petstore-client.ts
183
184
# Angular client with specific settings
185
nswag openapi2tsclient /input:api.json /output:api.client.ts /Template:Angular /HttpClass:HttpClient /ClassName:ApiClient
186
187
# Fetch-based client with module
188
nswag openapi2tsclient /input:api.json /output:client.ts /Template:Fetch /ModuleName:ApiClient
189
```
190
191
### OpenAPI to C# Client Generation
192
193
Generates C# client code from OpenAPI/Swagger specifications.
194
195
```bash { .api }
196
nswag openapi2csclient /input:InputFile /output:OutputFile [options]
197
```
198
199
**Basic Configuration:**
200
- `/ClassName:ClassName` - Class name of the generated client
201
- `/ClientBaseClass:BaseClass` - Client base class (empty for no base class)
202
- `/ConfigurationClass:ConfigClass` - Configuration class (ClientBaseClass must be set)
203
- `/GenerateClientClasses:Boolean` - Generate client classes (default: true)
204
- `/GenerateClientInterfaces:Boolean` - Generate interfaces for client classes (default: false)
205
- `/ClientBaseInterface:Interface` - Base interface for client interfaces
206
- `/InjectHttpClient:Boolean` - Inject HttpClient instance (default: true)
207
- `/DisposeHttpClient:Boolean` - Dispose HttpClient (injected HttpClient never disposed, default: true)
208
209
**Exception Handling:**
210
- `/GenerateExceptionClasses:Boolean` - Generate exception classes (default: true)
211
- `/ExceptionClass:ClassName` - Exception class name (default: 'SwaggerException')
212
- `/WrapDtoExceptions:Boolean` - Wrap DTO exceptions in SwaggerException (default: true)
213
214
**HTTP Configuration:**
215
- `/UseHttpClientCreationMethod:Boolean` - Call CreateHttpClientAsync on base class
216
- `/HttpClientType:Type` - HttpClient type (default: 'System.Net.Http.HttpClient')
217
- `/UseHttpRequestMessageCreationMethod:Boolean` - Call CreateHttpRequestMessageAsync
218
- `/UseBaseUrl:Boolean` - Use and expose base URL (default: true)
219
- `/GenerateBaseUrlProperty:Boolean` - Generate BaseUrl property (default: true)
220
221
**Method Generation:**
222
- `/GenerateSyncMethods:Boolean` - Generate synchronous methods (default: false)
223
- `/GeneratePrepareRequestAndProcessResponseAsAsyncMethods:Boolean` - Generate async prepare/process methods
224
- `/ExposeJsonSerializerSettings:Boolean` - Expose JsonSerializerSettings property
225
- `/GenerateUpdateJsonSerializerSettingsMethod:Boolean` - Generate UpdateJsonSerializerSettings method
226
227
**Code Style:**
228
- `/ClientClassAccessModifier:Modifier` - Client class access modifier (default: public)
229
- `/TypeAccessModifier:Modifier` - DTO class/enum access modifier (default: public)
230
- `/PropertySetterAccessModifier:Modifier` - Property setter access modifier
231
- `/GenerateNativeRecords:Boolean` - Generate C# 9.0 record types (default: false)
232
- `/UseRequiredKeyword:Boolean` - Use C# 11 'required' keyword (default: false)
233
234
**Contracts Output:**
235
- `/GenerateContractsOutput:Boolean` - Generate separate contracts file
236
- `/ContractsNamespace:Namespace` - Contracts .NET namespace
237
- `/ContractsOutput:FilePath` - Contracts output file path
238
239
**Parameter Formatting:**
240
- `/ParameterDateTimeFormat:Format` - DateTime parameter format (default: 's')
241
- `/ParameterDateFormat:Format` - Date parameter format (default: 'yyyy-MM-dd')
242
- `/QueryNullValue:Value` - Null value for query parameters (default: '')
243
244
**Advanced Options:**
245
- `/OperationGenerationMode:Mode` - Operation generation mode (SingleClientFromOperationId or MultipleClientsFromPathSegments)
246
- `/AdditionalNamespaceUsages:Namespaces` - Additional namespace usages (comma separated)
247
- `/AdditionalContractNamespaceUsages:Namespaces` - Additional contract namespace usages (comma separated)
248
- `/GenerateOptionalParameters:Boolean` - Generate optional parameters (default: false)
249
- `/GenerateJsonMethods:Boolean` - Generate ToJson()/FromJson() methods (default: true)
250
- `/EnforceFlagEnums:Boolean` - Always generate enums as bit flags (default: false)
251
- `/SerializeTypeInformation:Boolean` - Serialize type information in $type property
252
- `/UseRequestAndResponseSerializationSettings:Boolean` - Different request/response serialization settings
253
- `/ProtectedMethods:Methods` - Methods with protected access modifier (comma separated)
254
- `/SuppressClientClassesOutput:Boolean` - Suppress client classes output
255
- `/SuppressClientInterfacesOutput:Boolean` - Suppress client interfaces output
256
257
**Usage Examples:**
258
259
```bash
260
# Basic C# client generation
261
nswag openapi2csclient /input:petstore.json /output:PetstoreClient.cs
262
263
# Custom namespace and class name
264
nswag openapi2csclient /input:api.json /output:Client.cs /Namespace:MyApp.Clients /ClassName:ApiClient
265
266
# Generate with interfaces and modern C# features
267
nswag openapi2csclient /input:api.json /output:Client.cs /GenerateClientInterfaces:true /GenerateNativeRecords:true /UseRequiredKeyword:true
268
269
# Generate separate contracts file
270
nswag openapi2csclient /input:api.json /output:Client.cs /GenerateContractsOutput:true /ContractsOutput:Contracts.cs /ContractsNamespace:MyApp.Contracts
271
```
272
273
### OpenAPI to C# Controller Generation
274
275
Generates C# Web API controller code from OpenAPI/Swagger specifications for contract-first development.
276
277
```bash { .api }
278
nswag openapi2cscontroller /input:InputFile /output:OutputFile [options]
279
```
280
281
**Configuration Options:**
282
- `/ClassName:ClassName` - Generated controller class name
283
- `/ControllerBaseClass:BaseClass` - Controller base class (empty for 'ApiController')
284
- `/ControllerStyle:Style` - Controller generation style (partial or abstract, default: partial)
285
- `/ControllerTarget:Target` - Controller target framework (default: AspNetCore)
286
- `/UseCancellationToken:Boolean` - Add cancellation token parameter (default: false)
287
- `/UseActionResultType:Boolean` - Use ASP.NET Core ActionResult type (default: false)
288
- `/GenerateModelValidationAttributes:Boolean` - Add model validation attributes (default: false)
289
- `/RouteNamingStrategy:Strategy` - Route naming strategy (none or operationid, default: none)
290
- `/BasePath:Path` - Base path for the API relative to host
291
292
**Usage Examples:**
293
294
```bash
295
# Generate controllers from OpenAPI spec
296
nswag openapi2cscontroller /input:api.json /output:Controllers.cs
297
298
# Generate with custom namespace and ASP.NET Core features
299
nswag openapi2cscontroller /input:api.json /output:Controllers.cs /Namespace:MyApp.Controllers /UseActionResultType:true /UseCancellationToken:true
300
301
# Generate abstract controllers with validation attributes
302
nswag openapi2cscontroller /input:api.json /output:Controllers.cs /ControllerStyle:abstract /GenerateModelValidationAttributes:true
303
```
304
305
### ASP.NET Core to OpenAPI Generation
306
307
Generates OpenAPI/Swagger specifications from ASP.NET Core applications using ApiExplorer.
308
309
```bash { .api }
310
nswag aspnetcore2openapi /Project:ProjectFile /output:OutputFile [options]
311
```
312
313
**Project Configuration:**
314
- `/Project:ProjectFile` - The project file to use (.csproj)
315
- `/DocumentName:Name` - Document name in SwaggerDocumentProvider (default: v1)
316
- `/MSBuildProjectExtensionsPath:Path` - MSBuild project extensions path (default: "obj")
317
- `/Configuration:Config` - Configuration to use (Debug, Release, etc.)
318
- `/Runtime:Runtime` - Runtime to use (e.g., net8.0)
319
- `/TargetFramework:Framework` - Target framework to use
320
- `/NoBuild:Boolean` - Don't build project (use when build is up-to-date)
321
- `/MSBuildOutputPath:Path` - MSBuild output path
322
- `/Verbose:Boolean` - Print verbose output (default: true)
323
- `/WorkingDirectory:Directory` - Working directory to use
324
- `/AspNetCoreEnvironment:Environment` - Set ASPNETCORE_ENVIRONMENT variable
325
326
**Usage Examples:**
327
328
```bash
329
# Generate OpenAPI from ASP.NET Core project
330
nswag aspnetcore2openapi /Project:MyApi.csproj /output:api.json
331
332
# Generate with specific configuration and environment
333
nswag aspnetcore2openapi /Project:MyApi.csproj /output:swagger.json /Configuration:Release /AspNetCoreEnvironment:Production
334
335
# Generate without building (when up-to-date)
336
nswag aspnetcore2openapi /Project:MyApi.csproj /output:api.json /NoBuild:true
337
338
# Generate for specific target framework
339
nswag aspnetcore2openapi /Project:MyApi.csproj /output:api.json /TargetFramework:net8.0
340
```
341
342
### JSON Schema to TypeScript Generation
343
344
Generates TypeScript interfaces from JSON Schema.
345
346
```bash { .api }
347
nswag jsonschema2tsclient /input:InputFile /output:OutputFile /Name:TypeName [options]
348
```
349
350
**Required Parameters:**
351
- `/Name:TypeName` - Type name of the root schema
352
353
**Configuration Options:**
354
- `/Namespace:Namespace` - TypeScript namespace (default: '', no namespace)
355
- `/TypeScriptVersion:Version` - Target TypeScript version (default: 2.7)
356
- `/DateTimeType:Type` - Date time type (Date, MomentJS, Luxon, DayJS, OffsetMomentJS, string)
357
- `/NullValue:NullValue` - Null value in object initializers (Undefined or Null)
358
- `/GenerateConstructorInterface:Boolean` - Generate constructor interface (default: true)
359
- `/TypeStyle:TypeStyle` - Type style (Class or Interface, default: Interface)
360
- `/EnumStyle:EnumStyle` - Enum style (Enum or StringLiteral, default: Enum)
361
- `/ExportTypes:Boolean` - Add export keyword to types (default: true)
362
- `/MarkOptionalProperties:Boolean` - Mark optional properties with ? (default: false)
363
364
**Usage Examples:**
365
366
```bash
367
# Generate TypeScript interfaces from JSON Schema
368
nswag jsonschema2tsclient /input:schema.json /output:types.ts /Name:MySchema
369
370
# Generate with custom namespace and type configuration
371
nswag jsonschema2tsclient /input:schema.json /output:types.ts /Name:ApiTypes /Namespace:MyApp.Types /TypeStyle:Class
372
373
# Generate with modern TypeScript features
374
nswag jsonschema2tsclient /input:schema.json /output:types.ts /Name:Schema /TypeScriptVersion:5.0 /MarkOptionalProperties:true
375
```
376
377
### JSON Schema to C# Generation
378
379
Generates C# classes from JSON Schema.
380
381
```bash { .api }
382
nswag jsonschema2csclient /input:InputFile /output:OutputFile /Name:ClassName /Namespace:Namespace [options]
383
```
384
385
**Required Parameters:**
386
- `/Name:ClassName` - Class name of the root schema
387
- `/Namespace:Namespace` - Namespace of generated classes
388
389
**Type Configuration:**
390
- `/RequiredPropertiesMustBeDefined:Boolean` - Required properties must be in JSON (default: true)
391
- `/DateType:Type` - Date .NET type (default: 'DateTimeOffset')
392
- `/DateTimeType:Type` - DateTime .NET type (default: 'DateTimeOffset')
393
- `/TimeType:Type` - Time .NET type (default: 'TimeSpan')
394
- `/TimeSpanType:Type` - TimeSpan .NET type (default: 'TimeSpan')
395
- `/AnyType:Type` - Any .NET type (default: 'object')
396
- `/ArrayType:Type` - Generic array .NET type (default: 'ICollection')
397
- `/ArrayInstanceType:Type` - Generic array .NET instance type (default: 'Collection')
398
- `/JsonConverters:Converters` - Custom Json.NET converter types (comma separated)
399
400
**Code Generation:**
401
- `/GenerateNativeRecords:Boolean` - Generate C# 9.0 record types (default: false)
402
- `/UseRequiredKeyword:Boolean` - Use C# 11 'required' keyword (default: false)
403
- `/ClassStyle:Style` - Class style (Poco, Record, default: Poco)
404
- `/GenerateDataAnnotations:Boolean` - Generate System.ComponentModel.DataAnnotations attributes
405
- `/GenerateJsonMethods:Boolean` - Generate ToJson()/FromJson() methods (default: true)
406
- `/GenerateDefaultValues:Boolean` - Generate default property values (default: true)
407
408
**Usage Examples:**
409
410
```bash
411
# Generate C# classes from JSON Schema
412
nswag jsonschema2csclient /input:schema.json /output:Models.cs /Name:RootModel /Namespace:MyApp.Models
413
414
# Generate with modern C# features and data annotations
415
nswag jsonschema2csclient /input:schema.json /output:Models.cs /Name:ApiModel /Namespace:MyApp.Models /GenerateNativeRecords:true /GenerateDataAnnotations:true
416
417
# Generate with custom types and converters
418
nswag jsonschema2csclient /input:schema.json /output:Models.cs /Name:Model /Namespace:MyApp /DateTimeType:DateTime /ArrayType:List /JsonConverters:MyConverter
419
```
420
421
### Configuration File Management
422
423
Creates and executes NSwag configuration files.
424
425
```bash { .api }
426
# Create new configuration file
427
nswag new
428
429
# Execute configuration file
430
nswag run [configFile.nswag]
431
```
432
433
**Usage Examples:**
434
435
```bash
436
# Create new nswag.json configuration in current directory
437
nswag new
438
439
# Execute specific configuration file
440
nswag run api-config.nswag
441
442
# Execute all .nswag files in current directory (if no input specified)
443
nswag run
444
```
445
446
### Runtime Selection
447
448
All commands support runtime selection to control which .NET runtime executes the command.
449
450
```bash { .api }
451
nswag <command> [options] [/runtime:Runtime]
452
```
453
454
**Runtime Options:**
455
- `/runtime:WinX86` - Full .NET Framework x86 mode (Windows only)
456
- `/runtime:NetCore` - Auto-detect latest supported .NET Core version
457
- `/runtime:Net80` - .NET 8.0 runtime (default)
458
- `/runtime:Net90` - .NET 9.0 runtime
459
460
**Legacy Options (deprecated):**
461
- `--x86` - Equivalent to `/runtime:WinX86`
462
- `--core` - Equivalent to `/runtime:Net80`
463
464
**Usage Examples:**
465
466
```bash
467
# Use specific .NET runtime
468
nswag version /runtime:Net90
469
470
# Use .NET Core auto-detection
471
nswag openapi2tsclient /input:api.json /output:client.ts /runtime:NetCore
472
473
# Legacy syntax (still supported)
474
nswag version --core
475
```
476
477
## Common Parameters
478
479
Most commands support these common parameters:
480
481
### Input/Output Parameters
482
- `/input:FilePath` - Input file path (OpenAPI spec, JSON schema, assembly, etc.) or URL
483
- `/output:FilePath` - Output file path for generated code (optional, defaults to console output)
484
- `/newLineBehavior:Behavior` - New line behavior (Auto, CRLF, LF)
485
486
### Service Configuration Parameters
487
- `/serviceHost:Host` - Overrides the service host of the web document (use '.' to remove hostname)
488
- `/serviceSchemes:Schemes` - Overrides allowed schemes (comma separated: 'http', 'https', 'ws', 'wss')
489
490
### Runtime Parameters
491
- `/runtime:Runtime` - .NET runtime to use for execution
492
493
## Error Handling
494
495
The CLI wrapper provides:
496
- Runtime detection and validation
497
- Clear error messages for missing .NET installations
498
- Exit code propagation from underlying .NET commands
499
- Validation of runtime parameters and command syntax
500
501
Commands exit with status code 0 on success or non-zero on failure, making them suitable for CI/CD integration.
502
503
## Configuration Files
504
505
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.
506
507
### Configuration File Structure
508
509
```json
510
{
511
"runtime": "Net80",
512
"defaultVariables": null,
513
"documentGenerator": {
514
"fromDocument": {
515
"url": "https://api.example.com/swagger.json",
516
"output": null,
517
"newLineBehavior": "Auto"
518
}
519
},
520
"codeGenerators": {
521
"openApiToCSharpClient": {
522
"clientBaseClass": null,
523
"configurationClass": null,
524
"generateClientClasses": true,
525
"generateClientInterfaces": false,
526
"clientBaseInterface": null,
527
"injectHttpClient": true,
528
"disposeHttpClient": true,
529
"protectedMethods": [],
530
"generateExceptionClasses": true,
531
"exceptionClass": "ApiException",
532
"wrapDtoExceptions": true,
533
"useHttpClientCreationMethod": false,
534
"httpClientType": "System.Net.Http.HttpClient",
535
"useHttpRequestMessageCreationMethod": false,
536
"useBaseUrl": true,
537
"generateBaseUrlProperty": true,
538
"generateSyncMethods": false,
539
"generatePrepareRequestAndProcessResponseAsAsyncMethods": false,
540
"exposeJsonSerializerSettings": false,
541
"clientClassAccessModifier": "public",
542
"typeAccessModifier": "public",
543
"generateContractsOutput": false,
544
"contractsNamespace": null,
545
"contractsOutputFilePath": null,
546
"parameterDateTimeFormat": "s",
547
"parameterDateFormat": "yyyy-MM-dd",
548
"generateUpdateJsonSerializerSettingsMethod": true,
549
"useRequestAndResponseSerializationSettings": false,
550
"serializeTypeInformation": false,
551
"queryNullValue": "",
552
"className": "{controller}Client",
553
"operationGenerationMode": "SingleClientFromOperationId",
554
"additionalNamespaceUsages": [],
555
"additionalContractNamespaceUsages": [],
556
"generateOptionalParameters": false,
557
"generateJsonMethods": true,
558
"enforceFlagEnums": false,
559
"parameterArrayType": "System.Collections.Generic.IEnumerable",
560
"parameterDictionaryType": "System.Collections.Generic.IDictionary",
561
"responseArrayType": "System.Collections.Generic.ICollection",
562
"responseDictionaryType": "System.Collections.Generic.IDictionary",
563
"wrapResponses": false,
564
"wrapResponseMethods": [],
565
"generateResponseClasses": true,
566
"responseClass": "SwaggerResponse",
567
"namespace": "MyNamespace",
568
"requiredPropertiesMustBeDefined": true,
569
"dateType": "System.DateTimeOffset",
570
"jsonConverters": null,
571
"anyType": "object",
572
"dateTimeType": "System.DateTimeOffset",
573
"timeType": "System.TimeSpan",
574
"timeSpanType": "System.TimeSpan",
575
"arrayType": "System.Collections.Generic.ICollection",
576
"arrayInstanceType": "System.Collections.ObjectModel.Collection",
577
"dictionaryType": "System.Collections.Generic.IDictionary",
578
"dictionaryInstanceType": "System.Collections.Generic.Dictionary",
579
"arrayBaseType": "System.Collections.ObjectModel.Collection",
580
"dictionaryBaseType": "System.Collections.Generic.Dictionary",
581
"classStyle": "Poco",
582
"jsonLibrary": "NewtonsoftJson",
583
"generateDefaultValues": true,
584
"generateDataAnnotations": false,
585
"excludedTypeNames": [],
586
"excludedParameterNames": [],
587
"handleReferences": false,
588
"generateImmutableArrayProperties": false,
589
"generateImmutableDictionaryProperties": false,
590
"jsonSerializerSettingsTransformationMethod": null,
591
"inlineNamedArrays": false,
592
"inlineNamedDictionaries": false,
593
"inlineNamedTuples": true,
594
"inlineNamedAny": false,
595
"generateDtoTypes": true,
596
"generateOptionalPropertiesAsNullable": false,
597
"generateNullableReferenceTypes": false,
598
"templateDirectory": null,
599
"typeNameGeneratorType": null,
600
"propertyNameGeneratorType": null,
601
"enumNameGeneratorType": null,
602
"serviceHost": null,
603
"serviceSchemes": null,
604
"output": "Generated/ApiClient.cs"
605
},
606
"openApiToTypeScriptClient": {
607
"className": "{controller}Client",
608
"moduleName": "",
609
"namespace": "",
610
"typeScriptVersion": 2.7,
611
"template": "Angular",
612
"promiseType": "Promise",
613
"httpClass": "HttpClient",
614
"withCredentials": false,
615
"useSingletonProvider": false,
616
"injectionTokenType": "InjectionToken",
617
"rxJsVersion": 6.0,
618
"dateTimeType": "Date",
619
"nullValue": "Undefined",
620
"generateClientClasses": true,
621
"generateClientInterfaces": false,
622
"generateOptionalParameters": false,
623
"exportTypes": true,
624
"wrapDtoExceptions": false,
625
"exceptionClass": "ApiException",
626
"clientBaseClass": null,
627
"wrapResponses": false,
628
"wrapResponseMethods": [],
629
"generateResponseClasses": true,
630
"responseClass": "SwaggerResponse",
631
"protectedMethods": [],
632
"configurationClass": null,
633
"useTransformOptionsMethod": false,
634
"useTransformResultMethod": false,
635
"generateDtoTypes": true,
636
"operationGenerationMode": "SingleClientFromOperationId",
637
"markOptionalProperties": false,
638
"generateCloneMethod": false,
639
"typeStyle": "Class",
640
"enumStyle": "Enum",
641
"useLeafType": false,
642
"classTypes": [],
643
"extendedClasses": [],
644
"extensionCode": null,
645
"generateDefaultValues": true,
646
"excludedTypeNames": [],
647
"excludedParameterNames": [],
648
"handleReferences": false,
649
"generateTypeCheckFunctions": false,
650
"generateConstructorInterface": true,
651
"convertConstructorInterfaceData": false,
652
"importRequiredTypes": true,
653
"useGetBaseUrlMethod": false,
654
"baseUrlTokenName": "API_BASE_URL",
655
"queryNullValue": "",
656
"useAbortSignal": false,
657
"inlineNamedDictionaries": false,
658
"inlineNamedAny": false,
659
"includeHttpContext": false,
660
"templateDirectory": null,
661
"typeNameGeneratorType": null,
662
"propertyNameGeneratorType": null,
663
"enumNameGeneratorType": null,
664
"serviceHost": null,
665
"serviceSchemes": null,
666
"output": "Generated/api-client.ts"
667
}
668
}
669
}
670
```
671
672
### Using Configuration Files
673
674
```bash
675
# Create a new configuration file with default settings
676
nswag new
677
678
# Execute a specific configuration file
679
nswag run myproject.nswag
680
681
# Execute all .nswag files in current directory
682
nswag run
683
684
# Execute with variables
685
nswag run /Variables:"baseUrl=https://api.example.com,version=v2"
686
```
687
688
## Troubleshooting
689
690
### Common Issues and Solutions
691
692
**Error: "Could not detect .NET Core version"**
693
- Ensure .NET 8.0+ or .NET 9.0+ is installed on your system
694
- Verify installation with: `dotnet --version`
695
- On Linux/macOS, install .NET runtime: `sudo apt-get install dotnet-runtime-8.0`
696
697
**Error: "Unsupported /runtime: argument"**
698
- Check available runtime options: WinX86, NetCore, Net80, Net90
699
- Use `/runtime:NetCore` for automatic detection of latest installed version
700
- Verify .NET installation matches the specified runtime
701
702
**Error: "The full .NET Framework installation not found"**
703
- This occurs on Windows when trying to use `/runtime:WinX86` without full .NET Framework
704
- Install .NET Framework 4.6.2+ or use .NET 8.0+ runtime instead
705
- Use `/runtime:Net80` for cross-platform compatibility
706
707
**Error: "Multiple /runtime:* arguments detected"**
708
- Remove legacy `--core` or `--x86` arguments when using `/runtime:` parameter
709
- Use only one runtime specification per command
710
711
**Error: "Input file not found" or network errors**
712
- Verify input file path or URL is accessible
713
- For URLs, ensure network connectivity and valid OpenAPI/Swagger endpoint
714
- Check file permissions for local files
715
716
**Performance Issues with Large Specifications**
717
- Use `/output:filename` to write to file instead of console output
718
- Consider breaking large specifications into smaller, focused schemas
719
- Increase available memory if generating large client libraries
720
721
**Generated Code Compilation Errors**
722
- Verify target framework compatibility between generated code and your project
723
- Check for missing NuGet package dependencies in generated clients
724
- Review namespace conflicts in generated code
725
726
### Getting Help
727
728
For additional help with specific commands:
729
```bash
730
nswag help [command]
731
```
732
733
For community support and detailed documentation:
734
- [NSwag Wiki](https://github.com/RicoSuter/NSwag/wiki)
735
- [GitHub Issues](https://github.com/RicoSuter/NSwag/issues)
736
- [Command Line Documentation](https://github.com/RicoSuter/NSwag/wiki/CommandLine)