AspNetCore.Docs/aspnetcore/tutorials/getting-started-with-NSwag.md

13 KiB

title author description ms.author ms.custom ms.date uid
Get started with NSwag and ASP.NET Core zuckerthoben Learn how to use NSwag to generate documentation and help pages for an ASP.NET Core web API. scaddie mvc 09/20/2018 tutorials/get-started-with-nswag

Get started with NSwag and ASP.NET Core

By Christoph Nienaber and Rico Suter

::: moniker range=">= aspnetcore-2.1"

View or download sample code (how to download)

::: moniker-end

::: moniker range="<= aspnetcore-2.0"

View or download sample code (how to download)

::: moniker-end

Register the NSwag middlewares to:

  • Generate the Swagger specification for the implemented web API.
  • Serve the Swagger UI to browse and test the web API.

To use the NSwag ASP.NET Core middlewares, install the NSwag.AspNetCore NuGet package. This package contains the middlewares to generate and serve the Swagger specification, Swagger UI (v2 and v3), and ReDoc UI.

Additionally, it's highly recommended to make use of NSwag's code generation capabilities. Choose one of the following options to use the code generation capabilities:

Features

The main reason to use NSwag is the ability to not only introduce the Swagger UI and Swagger generator, but to also make use of the flexible code generation capabilities. You don't need an existing API—you can use third-party APIs that incorporate Swagger and let NSwag generate a client implementation. Either way, the development cycle is expedited and you can more easily adapt to API changes.

Package installation

The NSwag NuGet package can be added with the following approaches:

Visual Studio

  • From the Package Manager Console window:

    • Go to View > Other Windows > Package Manager Console

    • Navigate to the directory in which the TodoApi.csproj file exists

    • Execute the following command:

      Install-Package NSwag.AspNetCore
      
  • From the Manage NuGet Packages dialog:

    • Right-click the project in Solution Explorer > Manage NuGet Packages
    • Set the Package source to "nuget.org"
    • Enter "NSwag.AspNetCore" in the search box
    • Select the "NSwag.AspNetCore" package from the Browse tab and click Install

Visual Studio for Mac

  • Right-click the Packages folder in Solution Pad > Add Packages...
  • Set the Add Packages window's Source drop-down to "nuget.org"
  • Enter "NSwag.AspNetCore" in the search box
  • Select the "NSwag.AspNetCore" package from the results pane and click Add Package

Visual Studio Code

Run the following command from the Integrated Terminal:

dotnet add TodoApi.csproj package NSwag.AspNetCore

.NET Core CLI

Run the following command:

dotnet add TodoApi.csproj package NSwag.AspNetCore

Add and configure Swagger middleware

Import the following namespaces in the Startup class:

[!code-csharp]

In the Startup.ConfigureServices method, register the required Swagger services:

[!code-csharp]

In the Startup.Configure method, enable the middleware for serving the generated Swagger specification and the Swagger UI v3:

[!code-csharp]

Launch the app. Navigate to http://localhost:<port>/swagger to view the Swagger UI. Navigate to http://localhost:<port>/swagger/v1/swagger.json to view the Swagger specification.

Code generation

Via NSwagStudio

  • Install NSwagStudio from the official GitHub repository.
  • Launch NSwagStudio. Enter the swagger.json file URL in the Swagger Specification URL textbox, and click the Create local Copy button.
  • Select the CSharp Client client output type. Other options include TypeScript Client and CSharp Web API Controller. Using a Web API Controller is basically a reverse generation. It uses a specification of a service to rebuild the service.
  • Click the Generate Outputs button. A complete C# client implementation of the TodoApi.NSwag project is produced. Click the CSharp Client tab of the Outputs section to see the generated client code:
//----------------------
// <auto-generated>
//     Generated using the NSwag toolchain v11.17.3.0 (NJsonSchema v9.10.46.0 (Newtonsoft.Json v9.0.0.0)) (http://NSwag.org)
// </auto-generated>
//----------------------

namespace MyNamespace
{
    #pragma warning disable // Disable all warnings

    [System.CodeDom.Compiler.GeneratedCode("NSwag",
        "11.17.3.0 (NJsonSchema v9.10.46.0 (Newtonsoft.Json v9.0.0.0))")]
    public partial class TodoClient
    {
        private string _baseUrl = "http://localhost:50499";
        private System.Lazy<Newtonsoft.Json.JsonSerializerSettings> _settings;

        public TodoClient()
        {
            _settings = new System.Lazy
                <Newtonsoft.Json.JsonSerializerSettings>(() =>
            {
                var settings = new Newtonsoft.Json.JsonSerializerSettings();
                UpdateJsonSerializerSettings(settings);
                return settings;
            });
        }

        public string BaseUrl
        {
            get { return _baseUrl; }
            set { _baseUrl = value; }
        }

        // code omitted for brevity

[!TIP] The C# client code is generated based on settings defined in the Settings tab of the CSharp Client tab. Modify the settings to perform tasks such as default namespace renaming and synchronous method generation.

  • Copy the generated C# code into a file in a client project (for example, a Xamarin.Forms app).
  • Start consuming the web API:
var todoClient = new TodoClient();

// Gets all to-dos from the API
var allTodos = await todoClient.GetAllAsync();

// Create a new TodoItem, and save it in the API
var createdTodo = await todoClient.CreateAsync(new TodoItem());

// Get a single to-do by ID
var foundTodo = await todoClient.GetByIdAsync(1);

[!NOTE] You can inject a base URL and/or a HTTP client into the API client. The best practice is to always reuse the HttpClient.

Other ways to generate client code

You can generate the client code in other ways, more suited to your workflow:

Customize

Swagger provides options for documenting the object model to ease consumption of the web API.

API info and description

In the Startup.Configure method, a configuration action passed to the UseSwagger method adds information such as the author, license, and description:

[!code-csharp]

The Swagger UI displays the version's information:

Swagger UI with version information

XML comments

XML comments are enabled with the following approaches:

Visual Studio

::: moniker range=">= aspnetcore-2.0"

  • Right-click the project in Solution Explorer and select Edit <project_name>.csproj.
  • Manually add the highlighted lines to the .csproj file:

[!code-xml]

::: moniker-end

::: moniker range="<= aspnetcore-1.1"

  • Right-click the project in Solution Explorer and select Properties
  • Check the XML documentation file box under the Output section of the Build tab

::: moniker-end

Visual Studio for Mac

::: moniker range=">= aspnetcore-2.0"

  • From the Solution Pad, press control and click the project name. Navigate to Tools > Edit File.
  • Manually add the highlighted lines to the .csproj file:

[!code-xml]

::: moniker-end

::: moniker range="<= aspnetcore-1.1"

  • Open the Project Options dialog > Build > Compiler
  • Check the Generate xml documentation box under the General Options section

::: moniker-end

Visual Studio Code

Manually add the highlighted lines to the .csproj file:

::: moniker range=">= aspnetcore-2.0"

[!code-xml]

::: moniker-end

::: moniker range="<= aspnetcore-1.1"

[!code-xml]

::: moniker-end


Data annotations

::: moniker range="<= aspnetcore-2.0"

NSwag uses Reflection, and the recommended return type for web API actions is IActionResult. Consequently, NSwag can't infer what your action is doing and what it returns. Consider the following example:

[!code-csharp]

The preceding action returns IActionResult, but inside the action it's returning either CreatedAtRoute or BadRequest. Data annotations are used to tell clients which HTTP status codes this action is known to return. Decorate the action with the following attributes:

[!code-csharp]

::: moniker-end

::: moniker range=">= aspnetcore-2.1"

NSwag uses Reflection, and the recommended return type for web API actions is ActionResult<T>. Consequently, NSwag can only infer the return type defined by T. Other possible return types in the action cannot be inferred. Consider the following example:

[!code-csharp]

The preceding action returns ActionResult<T>, but inside the action it's returning either CreatedAtRoute. Since the controller is decorated with the [ApiController] attribute, a BadRequest response is possible too. See Automatic HTTP 400 responses for more info. Data annotations are used to tell clients which HTTP status codes this action is known to return. Decorate the action with the following attributes:

[!code-csharp]

::: moniker-end

The Swagger generator can now accurately describe this action, and generated clients know what they receive when calling the endpoint. Decorating all actions with these attributes is highly recommended. For guidelines on what HTTP responses your API actions should return, see the RFC 7231 specification.