在 .Net5 中,您可以在 Startup.cs 中将 SchemaFilter 添加到 Swagger
public override void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SchemaFilter<ExampleSchemaFilter>();
});
}
在 ExampleSchemaFilter.cs 中,您只需为特定类定义一个 OpenApiObject:
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
public class ExampleSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (context.Type == typeof(User))
{
schema.Example = new OpenApiObject()
{
["firstName"] = new OpenApiString("John"),
["lastName"] = new OpenApiString("Doe"),
};
}
}
}