Home > Software design >  Why swashbuckle example value does not work?
Why swashbuckle example value does not work?

Time:07-01

Here I added XML doc parameter example="this does not work" for swashbuckle framework.

/// <summary>Gets a user by id.</summary>
/// <param name="id" example="this does not work">The id of user.</param>
/// <returns>got user.</returns>
[HttpGet("Get")]
[ProducesResponseType(typeof(UserDTO), 200)]
[ProducesResponseType(typeof(AppException), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> Get(string id)
{
    return HandleResult(await _userServices.GetUserAsync(id));
}

But example value does not appear in Swagger UI.

enter image description here

Where I should look for the problem?

CodePudding user response:

Unfortunately out of the box Swashbuckle doesn't support the example tag/attribute. You need to write an operation filter and implement your own. Or you can use the Swashbuckle.AspNetCore.Filters nuget package.

You need to add the following code in your program.cs file.

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath, includeControllerXmlComments: true);
});
//For Example tag support
builder.Services.AddSwaggerExamplesFromAssemblies(Assembly.GetEntryAssembly());

And once you run the app you will be able to see examples like this in your swagger documentation.

Swagger documentation with Example

  • Related