I am assuming you are using .NET Core.
I have not tested this solution, but hopefully it is on the right track.
In your Startup
class, you are probably registering Swagger in the ConfigureServices
method, as well as your database context.
You need to add one line in AddSwaggerGen
to register a custom filter.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<YourContext>();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
// Custom filter (could also be a SchemaFilter)
c.ParameterFilter<CustomParametersFilter>();
});
}
Here is the CustomParametersFilter
class:
public class CustomParametersFilter : IParameterFilter
{
private readonly YourContext dbContext;
public CustomParametersFilter(YourContext dbContext)
{
// Here you also have access to IServiceProvider or any dependency
this.dbContext = dbContext;
}
public void Apply(IParameter parameter, ParameterFilterContext context)
{
if (parameter.Name == "some_name")
{
// Use dbContext to retrieve your values
List<string> validValues;
// ...
parameter.Description = string.Join(", ", validValues);
}
}
}
The code for CustomParametersFilter
is a starting point, but it can be adjusted to suit your needs. IParameter
(and OpenApiParameter
) offer many more options.