Skip to content

Instantly share code, notes, and snippets.

@joaofbantunes
Created February 19, 2022 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joaofbantunes/05ec7c20c1beb065a81c395067fc530e to your computer and use it in GitHub Desktop.
Save joaofbantunes/05ec7c20c1beb065a81c395067fc530e to your computer and use it in GitHub Desktop.
ASP.NET Core + Swashbuckle OpenAPI Extensions sample
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