Add Swagger Docs to .NET Project - gecko-8/devwiki GitHub Wiki

Up

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 Swagger/Swashbuckle to Project

  1. Add Swashbuckle.AspNetCore package to API project
  2. Add Swashbuckle.AspNetCore package to Models project (for comments)
  3. Enable Documentation in API project and Models project (in project Properties, Build tab)
  4. 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);
    });
    
  5. Add Swagger to the pipeline right after UseRouting
    app.UseSwagger();
    
  6. Test json
    http://localhost:<port>/swagger/v1/swagger.json
    

Add SwaggerUI

  1. Add swaggerUI to the pipeline after UseSwagger
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });
    
  2. Test SwaggerUI
    http://localhost:<port>/swagger
    

Add Authorization

  1. Add Swashbuckle folder to API project
  2. 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>()
            });
        }
    }    
    
  3. 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>();
    
  4. Test working
⚠️ **GitHub.com Fallback** ⚠️