August 10 2024
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
public class RemoveObsoleteOperationsFilter : IDocumentFilter {
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) {
var obsoletePaths = swaggerDoc.Paths
.Where(path => path.Value.Operations
.Any(op => op.Value.Deprecated))
.Select(path => path.Key)
.ToList();
foreach (var obsoletePath in obsoletePaths)
swaggerDoc.Paths.Remove(obsoletePath);
}
}
builder.Services.AddSwaggerGen(c =>
{
c.DocumentFilter<RemoveObsoleteOperationsFilter>();
});
public class AddGlobalMetadataDocumentFilter : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
foreach (var pathItem in swaggerDoc.Paths.Values)
{
foreach (var operation in pathItem.Operations.Values)
{
// Add a common description to all operations
operation.Description = operation.Description ?? "This is a common description for all operations.";
// Add a common tag to all operations
operation.Tags = operation.Tags ?? new List<OpenApiTag>();
operation.Tags.Add(new OpenApiTag { Name = "CommonTag" });
}
}
}
}
public class AddCustomHeaderToResponsesDocumentFilter : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
foreach (var pathItem in swaggerDoc.Paths.Values)
{
foreach (var operation in pathItem.Operations.Values)
{
foreach (var response in operation.Responses.Values)
response.Headers ??= new Dictionary<string, OpenApiHeader>();
response.Headers.Add("X-Custom-Header", new OpenApiHeader
{
Description = "This is a custom header added to all responses.",
Schema = new OpenApiSchema
{
Type = "string"
}
});
}
}
}
}
}
Join 13,250+ subscribers to improve your .NET Knowledge.
Go-to resource for understanding the core concepts of design patterns without the overwhelming complexity. In this concise and affordable ebook, I've distilled the essence of design patterns into an easy-to-digest format. It is a Beginner level. Check out it here.
Every Monday morning, I share 1 actionable tip on C#, .NET & Arcitecture topic, that you can use right away.
Subscribe to the TheCodeMan.net and be among the 13,250+ subscribers gaining practical tips and resources to enhance your .NET expertise.