Configure Swagger with XML Comments in .NET

Easily document your APIs with swagger in .net

ebeeraheem

View Profile
63 views
Jun 21, 2025
Updated Jun 30, 2025

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 // Optional step
builder.Services.AddSwaggerGen(options =>
{
   options.SwaggerDoc("v1", new OpenApiInfo()
   {
       Title = "My Awesome API",
       Version = "v1",
       Description = "An API that does awesome things.",
       Contact = new OpenApiContact()
       {
           Name = "Your Name",
           Email = "your@email.com",
           Url = new Uri("https://website.com")
       }
   });
   
   options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
   {
       Type = SecuritySchemeType.Http,
       In = ParameterLocation.Header,
       Name = "Authorization",
       Scheme = "bearer",
       BearerFormat = "JWT",
       Description = "Enter your token here:",
   });
   options.AddSecurityRequirement(new OpenApiSecurityRequirement()
   {
       {
           new OpenApiSecurityScheme
           {
               Reference = new OpenApiReference
               {
                   Type = ReferenceType.SecurityScheme,
                   Id = "Bearer",
               }
           },
           Array.Empty<string>()
       }
   });
   // Display XML comments in SwaggerUI
   var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
   var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
   options.IncludeXmlComments(xmlPath);
});