Details

Swagger Configurations

This is the complete swagger configuration options

NOTE: Before you can use xml comments, you need to do the following

  1. Right-click on the project and select properties
  2. In the Build tab of the project properties, check the box labeled Documentation file under Output
  3. Suppress warning 1591
builder.Services.AddSwaggerGen(options =>
{
   // Add the API info and description
   options.SwaggerDoc("v1", new OpenApiInfo()
   {
       Title = "Some Random API",
       Version = "v1",
       Description = "An API that does random things.",
       Contact = new OpenApiContact()
       {
           Name = "Ibrahim Suleiman",
           Email = "ebeeraheem@gmail.com",
           Url = new Uri("https://ebeesule.netlify.app")
       }
   });
   // Add the authorize button in the SwaggerUI
   options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
   {
       Type = SecuritySchemeType.Http,
       In = ParameterLocation.Header,
       Name = "Authorization",
       Scheme = "bearer",
       BearerFormat = "JWT",
       Description = "Enter your token here:",
   });
   // Add the lock icon to all endpoints in SwaggerUI
   options.AddSecurityRequirement(new OpenApiSecurityRequirement()
   {
       {
           new OpenApiSecurityScheme
           {
               Reference = new OpenApiReference
               {
                   Type = ReferenceType.SecurityScheme,
                   Id = "Bearer",
               }
           },
           Array.Empty<string>()
       }
   });
   // Add XML comments in SwaggerUI
   var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
   var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
   options.IncludeXmlComments(xmlPath);
});

To avoid hard-coding the swagger config values
Add the following section to appsettings.json

 "SwaggerDoc": {
   "Title": "",
   "Description": "",
   "Contact": {
     "Name": "",
     "Email": "",
     "Url": ""
   }
 }

And then get the values using any means you're most comfortable with.
For example:

// Get swagger config values from appsettings.json
var title = builder.Configuration.GetSection("SwaggerDoc:Title").Value;
var description = builder.Configuration.GetSection("SwaggerDoc:Description").Value;
var name = builder.Configuration.GetSection("SwaggerDoc:Contact:Name").Value;
var email = builder.Configuration.GetSection("SwaggerDoc:Contact:Email").Value;
var url = builder.Configuration.GetSection("SwaggerDoc:Contact:Url").Value;