NSwag Documentation

repository·master·Indexed 27 days ago

https://github.com/ricosuter/nswag

A 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.

Tokens
6.3K
Snippets
6
Records
40
Agent score
91%

What's inside NSwag

  1. Overview of NSwag toolchain

    master
    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.
  2. Ways to use the NSwag toolchain

    master

    You 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 .csproj tags (preview).
  3. Register NSwag Middlewares in ASP.NET Core

    master

    To 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
        }
    }
  4. Customize NSwag C# Client Generation Output

    master

    To customize the generated C# client, interface, and DTOs, modify the following keys in your .nswag configuration file:

    • OpenAPI Spec Location: Set documentGenerator.fromDocument.url to the HTTP address or local file path of your spec.
    • Client Class Name: Set codeGenerators.openApiToCSharpClient.className (e.g., change SampleService to your desired name).
    • Client Namespace: Set codeGenerators.openApiToCSharpClient.namespace.
    • Output File Path: Set codeGenerators.openApiToCSharpClient.output to 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:

    1. Set codeGenerators.openApiToCSharpClient.generateContractsOutput to true.
    2. Set codeGenerators.openApiToCSharpClient.contractsNamespace to your desired contracts namespace.
    3. Set codeGenerators.openApiToCSharpClient.contractsOutputFilePath to the desired output path.

    Client Configuration

    • Base Class: If you are not using a base class beyond the generated interface, set codeGenerators.openApiToCSharpClient.clientBaseClass to null and codeGenerators.openApiToCSharpClient.useHttpRequestMessageCreationMethod to false.
  5. Develop and build the NSwag NPM module

    master

    For 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 binaries directory.
    • Run locally: Navigate to the source directory and use node to run the binary.
    • Publish: Use the publish batch file (requires login).
  6. Install NSwag via NPM

    master

    You 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-dev
  7. Install NSwag via NuGet

    master

    NSwag 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 (for dotnet nswag), NSwag.MSBuild
  8. Generate Service Client Proxy code using NSwag CLI

    master

    You can automate the generation of service clients, interface definitions, and DTOs from an OpenAPI specification using the NSwag command-line tool.

    Prerequisites

    • Install the NSwag CLI tool.
    • Have an OpenAPI/Swagger specification available (either via a URL or a local JSON/YAML file).

    Basic Workflow (Using an existing config)

    1. Prepare your project folders (e.g., Services/[YourRemoteService] and Contracts/[YourRemoteService]).
    2. Ensure your .nswag configuration file points to the correct OpenAPI spec location.
    3. Run the following command to generate the code:
    nswag run sample.nswag /runtime:Net50

    Note: If your configuration specifies a specific runtime like Net50, you must include the /runtime:Net50 flag in your CLI command.

  9. Configure separate Contracts and Implementation output

    master

    To generate interfaces and models in a separate file from the client implementation, use the GenerateContractsOutput argument.

    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.

  10. Customize TypeScript DTO and Type Generation

    master

    When generating TypeScript clients, you can control how types and DTOs are structured using these settings:

    • TypeStyle: Set to Class (default) or Interface.
    • EnumStyle: Set to Enum (default) or StringLiteral.
    • 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 TypeStyle is Class), generates an interface for constructor initialization.
    • ConvertConstructorInterfaceData: If true, converts POJO objects in the constructor to DTO instances.
  11. Generate C# client code programmatically

    master

    You 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();