08

Lab 08 - Web API, DTOs, Swagger si JWT Authentication

Partea 3 din 6

Parte 3 — Swagger / OpenAPI

Pasul 6 — Configurare Swagger

Atenție la Swagger pe .NET 9 / .NET 10. În .NET 6–8, template-ul ASP.NET Core Web API includea Swashbuckle.AspNetCore by default în .csproj. Începând cu .NET 9, Microsoft a scos Swashbuckle din template și a introdus Microsoft.AspNetCore.OpenApi (alt API, minimal, fără UI built-in). Dacă folosiți .NET 9/10 sau proiect creat după 2025 — pachetul Swashbuckle nu e acolo, trebuie instalat manual:

dotnet add package Swashbuckle.AspNetCore --version 6.9.0

L-am făcut deja la Pasul 1, dar dacă ați sărit pasul ăla — acum e momentul. Fără pachet, AddSwaggerGen nu există și nu compilează.

Configurare în Program.cs

Adăugați înainte de var app = builder.Build();:

// Swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
    {
        Title = "News Portal API",
        Version = "v1",
        Description = "Web API pentru portalul de știri — Lab 8"
    });
});

Și după var app = builder.Build();, înainte de app.UseHttpsRedirection():

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "News Portal API v1");
        options.RoutePrefix = "swagger"; // UI la /swagger
    });
}

După rulare, accesați https://localhost:XXXX/swagger. Veți vedea toate endpoint-urile (MVC și API) — filtrați-le mental pe cele din api/....

Ce face [ApiController] pentru Swagger:

  • Descoperă automat parametrii din body vs query vs route
  • Deduce schema response-ului din tipul de return
  • Arată erorile de validare standard (ValidationProblemDetails)

Test în Swagger UI

  1. GET /api/articlesapi → „Try it out" → „Execute" → vedeți lista de articole (funcționează fără token, lectură publică).
  2. GET /api/articlesapi/1 → id = 1 → ok, id = 999 → 404.
  3. POST /api/articlesapi fără token → 401 Unauthorized. (După ce terminăm JWT, îl testăm cu token.)