Based on the Swagger documentation I must be able to add some examples for my class fields, something like:
But I can't find any way to add these examples to my classes.
Based on the Swagger documentation I must be able to add some examples for my class fields, something like:
But I can't find any way to add these examples to my classes.
You can enable XML Comments and then use the <example> element to define an example. Here's an example of using an <example>:
public class CompanyValidationResponse
{
/// <example>1234</example>
public int CompanyId { get; set; }
/// <example>Damage, Inc</example>
public string CompanyName { get; set; }
}
To do this first you need to add XML documentation to your class. Here is an example.
namespace WebApplication44
{
/// <summary>
/// Display Weather Forecast
/// </summary>
public class WeatherForecast
{
/// <summary>
/// Date of the weather
/// </summary>
public DateTime Date { get; set; }
/// <summary>
/// Temperature in Degree Celesuis
/// </summary>
public int TemperatureC { get; set; }
/// <summary>
/// Temperature in Fahrenheit
/// </summary>
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
/// <summary>
/// Summary of the Weather. It can be "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
/// </summary>
public string? Summary { get; set; }
}
}
Next, you need to enable the Documentation File > Generate a File containing API documentation option in the Project Properties in Visual Studio - No need to change the location.
Finally, modify the swagger generation code like this.
var xmlDoc = Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, "xml");
builder.Services.AddSwaggerGen(options => options.IncludeXmlComments(xmlDoc, true));
Then you will be able to see the Open API doc like this.