ASP.NET Core + Swashbuckle OpenAPI Extensions sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.OpenApi.Any; | |
using Microsoft.OpenApi.Extensions; | |
using Microsoft.OpenApi.Models; | |
using Swashbuckle.AspNetCore.SwaggerGen; | |
var builder = WebApplication.CreateBuilder(args); | |
builder.Services.AddEndpointsApiExplorer(); | |
builder.Services.AddSwaggerGen(c => | |
{ | |
c.SwaggerDoc("v1", new() {Title = builder.Environment.ApplicationName, Version = "v1"}); | |
c.DocumentFilter<GoogleOpenApiExtensions>(); | |
c.OperationFilter<SomeOtherOpenApiExtensions>(); | |
c.SchemaFilter<SomeOtherOpenApiExtensions>(); | |
// add more filters as needed | |
}); | |
var app = builder.Build(); | |
app.UseSwagger(); | |
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", $"{builder.Environment.ApplicationName} v1")); | |
app.MapGet("/", () => "Hello World!"); | |
app.Run(); | |
internal class GoogleOpenApiExtensions : IDocumentFilter | |
{ | |
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) | |
{ | |
swaggerDoc.AddExtension( | |
"x-google-backend", | |
new OpenApiObject | |
{ | |
["address"] = new OpenApiString("http://some.backend.url") | |
}); | |
} | |
} | |
internal class SomeOtherOpenApiExtensions : IOperationFilter, ISchemaFilter, IParameterFilter, IRequestBodyFilter | |
{ | |
public void Apply(OpenApiOperation operation, OperationFilterContext context) | |
{ | |
operation.AddExtension( | |
"x-some-operation-extension", | |
new OpenApiObject | |
{ | |
["random-operation-metadata-array"] = new OpenApiArray | |
{ | |
new OpenApiString("awesome-operation"), | |
new OpenApiInteger(9000) | |
}, | |
["some-boolean"] = new OpenApiBoolean(true) | |
}); | |
} | |
public void Apply(OpenApiSchema schema, SchemaFilterContext context) | |
{ | |
schema.AddExtension("x-some-schema-extension", new OpenApiString("hello!")); | |
} | |
public void Apply(OpenApiParameter parameter, ParameterFilterContext context) | |
{ | |
// parameter.AddExtension ... | |
} | |
public void Apply(OpenApiRequestBody requestBody, RequestBodyFilterContext context) | |
{ | |
// requestBody.AddExtension ... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment