Get started with NSwag and ASP.NET Core

[ad_1]


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:

  • 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

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:


public void Configure(IApplicationBuilder app)

    app.UseStaticFiles();

    // Enable the Swagger UI middleware and the Swagger generator
    app.UseSwaggerUi(typeof(Startup).GetTypeInfo().Assembly, settings =>
    
        settings.GeneratorSettings.DefaultPropertyNameHandling = PropertyNameHandling.CamelCase;
    );

    app.UseMvc();


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:

  • 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

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.




[ad_2]

source_link
https://www.asp.net