« Swashbuckle » : différence entre les versions
Apparence
Ligne 174 : | Ligne 174 : | ||
[ProducesResponseType(typeof(IEnumerable<Item>), StatusCodes.Status200OK)] | [ProducesResponseType(typeof(IEnumerable<Item>), StatusCodes.Status200OK)] | ||
public IActionResult GetAll() { /* ... */ } | public IActionResult GetAll() { /* ... */ } | ||
</filebox> | |||
== Document Filter == | |||
<filebox fn='Program.cs'> | |||
services.AddSwaggerGen(c => | |||
{ | |||
c.DocumentFilter<MyDocumentFilter>(); | |||
}); | |||
</filebox> | |||
<filebox fn='MyDocumentFilter.cs'> | |||
public class MyDocumentFilter : IDocumentFilter | |||
{ | |||
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) | |||
{ | |||
// add new property | |||
swaggerDoc.Extensions.Add("propertyName", new OpenApiObject | |||
{ | |||
["propertyName"] = new OpenApiString("value"), | |||
["propertyName"] = new OpenApiArray | |||
{ | |||
{ new OpenApiString("value") } | |||
} | |||
} | |||
} | |||
} | |||
</filebox> | </filebox> | ||
Version du 26 juin 2024 à 11:48
Liens
NSwag
Installation
# pour vscode
dotnet add package NSwag.AspNetCore
# Add to the project file *.csproj:
# <ItemGroup>
# <PackageReference Include="NSwag.AspNetCore" Version="11.17.15" />
|
Configuration
Configuration Web API
Program.cs |
builder.Services.AddSwaggerDocument(configuration =>
{
configuration.Title = "MyApp";
configuration.Version = typeof(Program).Assembly.GetSimplifiedVersion();
});
if (app.Environment.IsDevelopment())
{
app.UseOpenApi();
app.UseSwaggerUi3();
}
|
Configuration MVC
Startup.cs |
Problème avec IActionResult
NSwag utilise la réflexion pour obtenir le type de retour. Avec IActionResult il ne peut pas.
[HttpGet]
// utiliser SwaggerResponse
[SwaggerResponse(HttpStatusCode.OK, typeof(IReadOnlyList<ItemDto>))]
[SwaggerResponse(HttpStatusCode.BadRequest, typeof(void))]
// ou ProducesResponseType
[ProducesResponseType(typeof(IReadOnlyList<ItemDto>), StatusCodes.Status200OK)]
public IActionResult Get()
|
Swashbuckle
Swashbuckle installation
Already installed in .NET 7+
MyWebApi.csproj |
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
|
Program.cs |
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
if (app.Environment.IsDevelopment())
{
app.UseSwagger()
.UseSwaggerUI();
}
|
Installation Old
dotnet add package Swashbuckle.AspNetCore |
Startup.cs |
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "EFWebApi", Version = "v1" });
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "EFWebApi v1");
c.RoutePrefix = string.Empty; // serve the Swagger UI at the app's root (http://localhost:<port>/)
});
}
|
Usage
Controllers/ItemController.cs |
[ApiController]
[Route("[controller]")]
[Produces("application/json")] // set the Media type
public class ItemController : ControllerBase
{
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<Item>), StatusCodes.Status200OK)] // set the status code and the return type
public IActionResult Get() { /* ... */ }
}
|
XML documentation
MyProject.csproj |
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
|
Program.cs |
builder.Services.AddSwaggerGen(
options =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My Web Api", Version = "v1" });
// Set the comments path for the Swagger JSON and UI.
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
}
|
Controllers/ItemController.cs |
/// <summary>Fetch all the items.</summary>
/// <param name="cancellationToken"></param>
/// <returns>All the items</returns>
/// <remarks>
/// Sample request:
///
/// GET /item
/// </remarks>
/// <response code="200">Returns all the items.</response>
[HttpGet]
[Produces("text/json")]
[ProducesResponseType(typeof(IEnumerable<Item>), StatusCodes.Status200OK)]
public IActionResult GetAll() { /* ... */ }
|
Document Filter
Program.cs |
services.AddSwaggerGen(c =>
{
c.DocumentFilter<MyDocumentFilter>();
});
|
MyDocumentFilter.cs |
public class MyDocumentFilter : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
// add new property
swaggerDoc.Extensions.Add("propertyName", new OpenApiObject
{
["propertyName"] = new OpenApiString("value"),
["propertyName"] = new OpenApiArray
{
{ new OpenApiString("value") }
}
}
}
}
|
Dark theme
Startup.cs |
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "EFWebApi v1");
c.RoutePrefix = string.Empty;
c.InjectStylesheet("/swagger-ui/dark-theme.css");
});
}
|
wwwroot/swagger-ui/dark-theme.css |
Url
Url | Resource |
---|---|
http://localhost:<port>/swagger | swagger UI |
http://localhost:<port>/swagger/v1/swagger.json | swagger json |
Dans un projet Web API avec Visual Studio Code, ouvrir le navigateur sur la page swagger.
.vscode\launch.json |
{
"configurations": [
{
"serverReadyAction": {
"action": "openExternally",
"pattern": "^\\s*Now listening on:\\s+(https?://\\S+)",
"uriFormat": "%s/swagger"
},
// autre solution
"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"
}
}
|
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.