Add Swagger Docs to .NET Project - gecko-8/devwiki GitHub Wiki
NOTE: Models project steps are optional. Basically do those steps to any project (other than the API project) that you want to use the Swashbuckle comments (///) in.
- Add Swashbuckle.AspNetCore package to API project
- Add Swashbuckle.AspNetCore package to Models project (for comments)
- Enable Documentation in API project and Models project (in project Properties, Build tab)
- Initialize SwaggerGen in API project Startup.cs
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); var apiPath = Path.Combine(System.AppContext.BaseDirectory, "<project name>.xml"); var modelsPath = Path.Combine(System.AppContext.BaseDirectory, "<project name>.Models.xml"); c.IncludeXmlComments(apiPath); c.IncludeXmlComments(modelsPath); });
- Add Swagger to the pipeline right after UseRouting
app.UseSwagger();
- Test json
http://localhost:<port>/swagger/v1/swagger.json
- Add swaggerUI to the pipeline after UseSwagger
app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); });
- Test SwaggerUI
http://localhost:<port>/swagger
- Add Swashbuckle folder to API project
- Add AuthHeaderOperationFilter.cs class to Swashbuckle folder
public class AuthHeaderOperationFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { // Only authorize the endpoint if it has an Authorize attribute var isAuthorized = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any() || context.MethodInfo.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any(); if (!isAuthorized) return; // Add the Access Token parameter to the endpoint documentation if (operation.Security == null) operation.Security = new List<OpenApiSecurityRequirement>(); var scheme = new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "bearer" } }; operation.Security.Add(new OpenApiSecurityRequirement { [scheme] = new List<string>() }); } }
- Add SecurityDefinition and OperationFilter to AddSwaggerGen in API project Startup.cs
c.AddSecurityDefinition("bearer", new OpenApiSecurityScheme { Type = SecuritySchemeType.Http, BearerFormat = "JWT", In = ParameterLocation.Header, Scheme = "bearer" }); c.OperationFilter<AuthHeaderOperationFilter>();
- Test working