NSwag Documentation
repository·master·Indexed 27 days ago
https://github.com/ricosuter/nswagA comprehensive Swagger/OpenAPI 2.0 and 3.0 toolchain for .NET, Web API, and TypeScript. NSwag enables the generation of OpenAPI specifications from ASP.NET controllers and the creation of strongly-typed client code for platforms including Angular, React, and .NET. It is available via NSwagStudio (Windows GUI), CLI (NPM), NuGet packages, and as ASP.NET Core/OWIN middlewares.
What's inside NSwag
- NSwag is a Swagger/OpenAPI 2.0 and 3.0 toolchain designed for .NET, .NET Core, Web API, and ASP.NET Core. It provides tools to generate OpenAPI specifications from existing ASP.NET Web API controllers and to generate client code (C# or TypeScript) from those specifications. It combines the functionality of OpenAPI generation (like Swashbuckle) and client generation (like AutoRest) into a single toolchain.
Install NSwag via NPM
masterThe NSwag command line tools (.NET and .NET Core) are available as an NPM package.
npm install nswagWays to use the NSwag toolchain
masterYou can interact with NSwag through several interfaces:
- NSwagStudio: A Windows GUI for easy configuration.
- ASP.NET Core/OWIN Middlewares: Recommended for serving OpenAPI specs and UI (Swagger UI/ReDoc) directly from your application.
- Command Line (CLI): Supports Windows, Mac, and Linux (via Mono or .NET Core) and is available as an NPM package.
- C# Code: Use via NuGet packages for programmatic generation.
- MSBuild Targets: Integrate into your build process.
- ServiceProjectReference: Use
.csprojtags (preview).
Register NSwag Middlewares in ASP.NET Core
masterTo generate an OpenAPI spec and render the UI (Swagger UI or ReDoc) within your ASP.NET Core application, register the services and middlewares in
Startup.cs:public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddOpenApiDocument(); // add OpenAPI v3 document // services.AddSwaggerDocument(); // add Swagger v2 document } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseOpenApi(); // serve OpenAPI/Swagger documents app.UseSwaggerUi(); // serve Swagger UI app.UseReDoc(); // serve ReDoc UI } }Customize NSwag C# Client Generation Output
masterTo customize the generated C# client, interface, and DTOs, modify the following keys in your
.nswagconfiguration file:- OpenAPI Spec Location: Set
documentGenerator.fromDocument.urlto the HTTP address or local file path of your spec. - Client Class Name: Set
codeGenerators.openApiToCSharpClient.className(e.g., changeSampleServiceto your desired name). - Client Namespace: Set
codeGenerators.openApiToCSharpClient.namespace. - Output File Path: Set
codeGenerators.openApiToCSharpClient.outputto define where the generated C# code is saved.
Separate Contracts and DTOs
If you want the interface and DTOs in a separate file from the client class:
- Set
codeGenerators.openApiToCSharpClient.generateContractsOutputtotrue. - Set
codeGenerators.openApiToCSharpClient.contractsNamespaceto your desired contracts namespace. - Set
codeGenerators.openApiToCSharpClient.contractsOutputFilePathto the desired output path.
Client Configuration
- Base Class: If you are not using a base class beyond the generated interface, set
codeGenerators.openApiToCSharpClient.clientBaseClasstonullandcodeGenerators.openApiToCSharpClient.useHttpRequestMessageCreationMethodtofalse.
- OpenAPI Spec Location: Set
Develop and build the NSwag NPM module
masterFor contributors or developers working on the NSwag NPM module, use the following commands to compile binaries and run the tool locally.
- Compile and copy binaries: Run the build batch file to move console binaries into the
binariesdirectory. - Run locally: Navigate to the source directory and use
nodeto run the binary. - Publish: Use the publish batch file (requires login).
- Compile and copy binaries: Run the build batch file to move console binaries into the
Install NSwag via NPM
masterYou can install NSwag either globally on your system or as a development dependency within a specific project.
Prerequisite: This NPM module requires Full .NET Framework 4.6.2+ or .NET 6.0+ to be installed on your system.
# Global installation npm install nswag -g # Project installation (as a dev dependency) npm install nswag --save-devInstall NSwag via NuGet
masterNSwag is distributed via several NuGet packages depending on your needs:
- Specification:
NSwag.Core,NSwag.Core.Yaml,NSwag.Annotations - OpenAPI Generation:
NSwag.Generation,NSwag.Generation.WebApi,NSwag.Generation.AspNetCore - Code Generation:
NSwag.CodeGeneration,NSwag.CodeGeneration.CSharp,NSwag.CodeGeneration.TypeScript - ASP.NET/ASP.NET Core:
NSwag.AspNetCore,NSwag.AspNet.Owin,NSwag.AspNet.WebApi - CLI/Tools:
NSwag.ConsoleCore(fordotnet nswag),NSwag.MSBuild
- Specification:
Generate Service Client Proxy code using NSwag CLI
masterYou can automate the generation of service clients, interface definitions, and DTOs from an OpenAPI specification using the NSwag command-line tool.
Prerequisites
- Install the
NSwagCLI tool. - Have an OpenAPI/Swagger specification available (either via a URL or a local JSON/YAML file).
Basic Workflow (Using an existing config)
- Prepare your project folders (e.g.,
Services/[YourRemoteService]andContracts/[YourRemoteService]). - Ensure your
.nswagconfiguration file points to the correct OpenAPI spec location. - Run the following command to generate the code:
nswag run sample.nswag /runtime:Net50Note: If your configuration specifies a specific runtime like
Net50, you must include the/runtime:Net50flag in your CLI command.- Install the
Configure separate Contracts and Implementation output
masterTo generate interfaces and models in a separate file from the client implementation, use the
GenerateContractsOutputargument.When this is enabled, you should also specify:
ContractsNamespace: The .NET namespace for the generated contracts.ContractsOutput: The file path where the contracts should be saved.
The tool will then produce at least two outputs: one for the contracts and one for the implementation.
Customize TypeScript DTO and Type Generation
masterWhen generating TypeScript clients, you can control how types and DTOs are structured using these settings:
- TypeStyle: Set to
Class(default) orInterface. - EnumStyle: Set to
Enum(default) orStringLiteral. - GenerateDtoTypes: Toggle whether to generate DTO classes.
- MarkOptionalProperties: If true, marks optional properties with
?. - GenerateCloneMethod: If true, adds a
clone()method to DTO classes. - GenerateConstructorInterface: If true (and
TypeStyleisClass), generates an interface for constructor initialization. - ConvertConstructorInterfaceData: If true, converts POJO objects in the constructor to DTO instances.
- TypeStyle: Set to
Generate C# client code programmatically
masterYou can use the NSwag API to read an OpenAPI specification and generate C# client classes manually:
var document = await OpenApiDocument.FromFileAsync("openapi.json"); var clientSettings = new CSharpClientGeneratorSettings { ClassName = "MyClass", CSharpGeneratorSettings = { Namespace = "MyNamespace" } }; var clientGenerator = new CSharpClientGenerator(document, clientSettings); var code = clientGenerator.GenerateFile();