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

7.8 KiB

title author description manager ms.author ms.custom ms.date ms.prod ms.technology ms.topic 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 app. wpickett scaddie mvc 03/15/2018 asp.net-core aspnet article tutorials/get-started-with-nswag

Get started with NSwag and ASP.NET Core

By Christoph Nienaber and Rico Suter

Using NSwag with ASP.NET Core middleware requires the NSwag.AspNetCore NuGet package. The package consists of a Swagger generator, Swagger UI (v2 and v3), and ReDoc UI.

It's highly recommended to make use of NSwag's code generation capabilities. Choose one of the following options for code generation:

Features

The main reason to use NSwag is the ability to not only introduce the Swagger UI and Swagger generator, but to 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:

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

    • Right-click your 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.NSwag.csproj package NSwag.AspNetCore

.NET Core CLI

Run the following command:

dotnet add TodoApi.NSwag.csproj package NSwag.AspNetCore

Add and configure Swagger middleware

Import the following namespaces in the Info class:

using NSwag.AspNetCore;
using System.Reflection;
using NJsonSchema;

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

[!code-cs]

Launch the app. Navigate to /swagger to view the Swagger UI. Navigate to /swagger/v1/swagger.json to view the Swagger specification.

Code generation

Via NSwagStudio

  • Install NSwagStudio from the official GitHub repository.

  • Launch NSwagStudio. Enter the location of your swagger.json or copy it directly:

NSwagStudio

  • Indicate the desired client output type. Options include TypeScript Client, CSharp Client, or 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 Generate Outputs.

  • Here you see a complete client implementation of the TodoApi.NSwag sample in C#:

NSwagStudio-Output

  • Put the file into a client project (for example, a Xamarin.Forms app). Start consuming the API:
var todoClient = new TodoClient();

// Gets all Todos 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 Todo 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.

You can now start implementing your API into client projects easily.

Other ways to generate client code

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

Customization

XML comments

XML comments are enabled with the following approaches:

Visual Studio

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

Build tab of project properties

Visual Studio for Mac

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

General Options section of project options

Visual Studio Code

Manually add the following snippet to the .csproj file:

[!code-xml]


Data annotations

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

public IActionResult Create([FromBody] TodoItem item)
{
    if (item == null)
    {
        return BadRequest();
    }

    _context.TodoItems.Add(item);
    _context.SaveChanges();

     return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
}

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 response this action is returning. Decorate the action with the following attributes:

[HttpPost]
[ProducesResponseType(typeof(TodoItem), 201)] // Created
[ProducesResponseType(typeof(TodoItem), 400)] // BadRequest
public IActionResult Create([FromBody] TodoItem item)

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.