Swagger

De Banane Atomic
Révision datée du 7 août 2019 à 13:51 par Nicolas (discussion | contributions) (→‎Problème avec IActionResult)
(diff) ← Version précédente | Voir la version actuelle (diff) | Version suivante → (diff)
Aller à la navigationAller à la recherche

Liens

Ajout de NSwag à un projet .Net Core

Powershell.svg
# pour vscode
dotnet add MyProject.csproj package NSwag.AspNetCore
# Ajoute au fichier MyProject.csproj:
#  <ItemGroup> 
#    <PackageReference Include="NSwag.AspNetCore" Version="11.17.15" />
Url : http://localhost:<port>/swagger

Configuration

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

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMvc();

    // à ajouter avant app.UseSpa
    app.UseSwaggerUi(typeof(Startup).GetTypeInfo().Assembly, settings =>
    {
        settings.GeneratorSettings.DefaultPropertyNameHandling = PropertyNameHandling.CamelCase;
        settings.PostProcess = document =>
        {
            //document.Info.Version = "v1";
            document.Info.Title = "Test API";
            document.Info.Description = "A simple ASP.NET Core web API";
            //document.Info.TermsOfService = "None";
            document.Info.Contact = new NSwag.SwaggerContact
            {
                Name = "Nicolas",
                //Email = string.Empty,
                //Url = "https://twitter.com/spboyer"
            };
            /*document.Info.License = new NSwag.SwaggerLicense
            {
                Name = "Use under LICX",
                Url = "https://example.com/license"
            };*/
        };
    });

Problème avec IActionResult

NSwag utilise la réflexion pour obtenir le type de retour. Avec IActionResult il ne peut pas.

Csharp.svg
[HttpGet]
// utiliser SwaggerResponse
[SwaggerResponse(HttpStatusCode.OK, typeof(IEnumerable<Item>))]
[SwaggerResponse(HttpStatusCode.BadRequest, typeof(void))]
// ou ProducesResponseType
[ProducesResponseType(200, Type = typeof(IEnumerable<Item>))]
public IActionResult Get()

Paramètres optionnels

Swagger ne gère pas les paramètres optionnels s'ils font partie du chemin, il les considère comme des paramètres required.

Ouvrir le navigateur sur swagger

Dans un projet Web API avec Visual Studio Code, ouvrir le navigateur sur la page swagger.

.vscode\launch.json
"configurations": [
{
    "launchBrowser": {
        "enabled": true,
        "args": "${auto-detect-url}",
        "windows": {
            "command": "cmd.exe",
            "args": "/C start ${auto-detect-url}/swagger/index.html?url=/swagger/v1/swagger.json#!/Items"
        },