Overview of Swashbuckle.AspNetCore
masterswagger-codegen to generate client libraries for various platforms.repository·master·Indexed 26 days ago
https://github.com/domaindrivendev/swashbuckle.aspnetcoreAn OpenAPI (Swagger) tooling library for ASP.NET Core applications that automatically generates OpenAPI documentation (supporting Swagger 2.0 and OpenAPI 3.0/3.1) from application code. It includes an embedded Swagger UI for interactive API exploration and testing, and supports the generation of client libraries via tools like swagger-codegen. The library consists of core components for generation (SwaggerGen), exposure (Swagger), and visualization (SwaggerUI), with additional extensions for annotations, CLI export, and ReDoc integration.
swagger-codegen to generate client libraries for various platforms.Swashbuckle.AspNetCore is composed of three core packages that work together to provide automatically generated API documentation. You can install them individually or use the Swashbuckle.AspNetCore metapackage to install all three at once.
OpenApiDocument instances from your application endpoints (controllers, minimal APIs, etc.) and provides an ISwaggerProvider implementation.ISwaggerProvider from the DI container.In OpenAPI, an operationId must be unique across all operations. Swashbuckle.AspNetCore omits this by default. You can assign them using one of two methods:
Name property: Use the Name property on HTTP verb attributes (e.g., [HttpGet]).options.CustomOperationIds in your AddSwaggerGen configuration to define a naming convention based on the ApiDescription.// Option 1: Decorate routes
[HttpGet("{id}", Name = "GetProductById")]
public IActionResult Get(int id)
{
return Ok();
}
// Option 2: Custom strategy in Startup.cs
services.AddSwaggerGen(options =>
{
options.CustomOperationIds(apiDescription =>
{
return apiDescription.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null;
});
});Most swagger-ui configuration parameters are surfaced through the UseSwaggerUI options. Common examples include controlling model expansion depth, enabling filters, or enabling 'Try It Out' mode.
app.UseSwaggerUI(options =>
{
options.DefaultModelExpandDepth(2);
options.DefaultModelRendering(ModelRendering.Model);
options.DefaultModelsExpandDepth(-1);
options.DisplayOperationId();
options.DisplayRequestDuration();
options.DocExpansion(DocExpansion.None);
options.EnableDeepLinking();
options.EnableFilter();
options.EnablePersistAuthorization();
options.EnableTryItOutByDefault();
options.MaxDisplayedTags(5);
options.ShowExtensions();
options.ShowCommonExtensions();
options.EnableValidator();
options.SupportedSubmitMethods(SubmitMethod.Get, SubmitMethod.Head);
options.UseRequestInterceptor("(request) => { return request; }");
options.UseResponseInterceptor("(response) => { return response; }");
});By default, the CLI tool executes in a "default" web host. If your application requires a custom host environment (e.g., using a custom DI container like Autofac), you can implement a convention-based hook in your application.
The tool will look for a class that follows one of these two naming conventions:
SwaggerHostFactory containing a public static IHost CreateHost() method.SwaggerWebHostFactory containing a public static IWebHost CreateWebHost() method.public class SwaggerHostFactory
{
public static IHost CreateHost()
=> MyApplication.CreateHostBuilder([]).Build();
}To customize the visual appearance, add CSS files to your wwwroot folder and specify their relative paths using options.InjectStylesheet().
app.UseReDoc(options =>
{
options.InjectStylesheet("/redoc/custom.css");
});When using multiple documents, you must specify which actions belong to which document. You can do this via decoration or conventions.
Use the [ApiExplorerSettings] attribute and set the GroupName property to the document name (case-sensitive).
Implement IControllerModelConvention to group actions based on metadata like namespaces.
Use DocInclusionPredicate to define custom logic for including an ApiDescription in a document. This is useful when using external versioning attributes (like Microsoft.AspNetCore.Mvc.Versioning).
// Decorate action
[HttpPost]
[ApiExplorerSettings(GroupName = "v2")]
public void PostLine([FromBody] ProductLine product) { ... }
// Custom inclusion predicate
options.DocInclusionPredicate((docName, apiDesc) =>
{
if (!apiDesc.TryGetMethodInfo(out MethodInfo methodInfo))
{
return false;
}
var versions = methodInfo.DeclaringType?
.GetCustomAttributes(true)
.OfType<ApiVersionAttribute>()
.SelectMany(attribute => attribute.Versions) ?? [];
return versions.Any(version => $"v{version}" == docName);
});For advanced customization, you can provide your own index.html file. This requires adding the file as an EmbeddedResource in your project file and using IndexStream to provide the stream.
// In C#
app.UseSwaggerUI(options =>
{
options.IndexStream = () => typeof(Program).Assembly
.GetManifestResourceStream("CustomUIIndex.Swagger.index.html");
});<!-- In .csproj -->
<Project>
<ItemGroup>
<EmbeddedResource Include="CustomUIIndex.Swagger.index.html" />
</ItemGroup>
</Project>You can customize the browser tab/document title for the Redoc UI by setting the DocumentTitle property in the UseReDoc options.
app.UseReDoc(options =>
{
options.DocumentTitle = "My API Docs";
});By default, Swashbuckle generates a 200 OK response. If your method returns a specific object, the schema for that object is automatically included.
To specify different status codes, additional responses, or to describe responses when returning IActionResult, use the ASP.NET Core [ProducesResponseType] attribute.
[HttpPost("product/{id}")]
[ProducesResponseType(typeof(Product), 200)]
[ProducesResponseType(typeof(IDictionary<string, string>), 400)]
[ProducesResponseType(500)]
public IActionResult GetProductInfoById(int id)
{
return Ok();
}By default, Swashbuckle uses the controller name as the OpenAPI tag, which SwaggerUI uses for grouping. You can override this behavior using TagActionsBy to group operations by other criteria, such as the HTTP method.
services.AddSwaggerGen(options =>
{
options.TagActionsBy(api => [api.HttpMethod]);
});For advanced customization, you can provide your own index.html file. This requires adding the file as an EmbeddedResource in your project and providing a delegate to options.IndexStream that returns the manifest resource stream.
app.UseReDoc(options =>
{
options.IndexStream = () => typeof(Program).Assembly
.GetManifestResourceStream("CustomIndex.ReDoc.index.html"); // Requires file to be added as an embedded resource
});<Project>
<ItemGroup>
<EmbeddedResource Include="CustomIndex.ReDoc.index.html" />
</ItemGroup>
</Project>