Liens
Ajout de NSwag à un projet .Net Core
|
dotnet add MyProject.csproj package NSwag.AspNetCore
|
 |
Url : http://localhost:<port>/swagger |
Configuration Web API
Startup.cs
|
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerDocument();
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseOpenApi();
app.UseSwaggerUi3();
|
Configuration MVC
Startup.cs
|
using NJsonSchema;
using NSwag.AspNetCore;
using System.Reflection;
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc();
app.UseSwaggerUi(typeof(Startup).GetTypeInfo().Assembly, settings =>
{
settings.GeneratorSettings.DefaultPropertyNameHandling = PropertyNameHandling.CamelCase;
settings.PostProcess = document =>
{
document.Info.Title = "Test API";
document.Info.Description = "A simple ASP.NET Core web API";
document.Info.Contact = new NSwag.SwaggerContact
{
Name = "Nicolas",
};
};
});
|
Problème avec IActionResult
NSwag utilise la réflexion pour obtenir le type de retour. Avec IActionResult il ne peut pas.
|
[HttpGet]
[SwaggerResponse(HttpStatusCode.OK, typeof(IReadOnlyList<ItemDto>))]
[SwaggerResponse(HttpStatusCode.BadRequest, typeof(void))]
[ProducesResponseType(typeof(IReadOnlyList<ItemDto>), StatusCodes.Status200OK)]
public IActionResult Get()
|
Test
- http://localhost:<port>/swagger
- http://localhost:<port>/swagger/v1/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"
},
"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.