Introduction
ASP.NET 6 Add swagger comments. What is this? This is a way you can add additional annotation (or notes/documentation) to your ASP.NET Swagger page. In this post, I’ll explain how you can do this.
Adding additional comments to Swagger is useful as usually the actual controller contract and request/response information isn’t enough for users. In this case, it’s a good practice to add additional comments to Swagger using this method below.
ASP.NET 6 Add swagger comments
Step 1: Add XML documentation to your controllers. This will be used by ASP.NET when it comes to generate the XML documentation file which is then used by Swagger.
/// <summary>
/// Gets the price for a ticker symbol
/// </summary>
/// <param name="tickerSymbol"></param>
/// <returns>A SharePriceResponse which contains the price of the share</returns>
/// <response code="200">Returns 200 and the share price</response>
/// <response code="400">Returns 400 if the query is invalid</response>
[HttpGet]
public async Task<ActionResult<SharePriceResponse>> GetPrice([FromQuery] string tickerSymbol)
{
var sharePriceQueryResponse = await _mediator.Send(new GetSharePriceQuery(tickerSymbol));
return new OkObjectResult(BuildSharePriceQueryResponse(sharePriceQueryResponse.SharePrice));
}
Step 2: Configure swagger gen to use the generated XML comments file. See line 22 which uses the AddSwaggerDocumentation()
method on line 43 to configure the Swagger generation to use the generated XML file. Note that this XML file named the same as the .NET project that contains your controllers.
using LSE.Stocks.Api.Middleware;
using LSE.Stocks.Api.ServiceCollectionExtensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.IO;
using System.Reflection;
namespace LSE.Stocks.Api;
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration) => Configuration = configuration;
public void ConfigureServices(IServiceCollection services)
=> services.AddEndpointsApiExplorer()
.AddSwaggerGen(o => AddSwaggerDocumentation(o))
.AddMediatorServices()
.AddRepositories(Configuration)
.AddControllers();
public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseCustomExceptionHandler();
app.UseEndpoints(endpoints => endpoints.MapControllers());
}
private static void AddSwaggerDocumentation(SwaggerGenOptions o)
{
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
o.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
}
}
Step 3: Configure .NET to generate the documentation file. To do this, add lines 7 and 8 to your .csproj
file. The NoWarn
block here specifies that .NET won’t warn for missing comments on other methods as it’ll do this for all methods in your project. See more information about that warning here.
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<UserSecretsId>af936c22-e0f8-45da-8f5f-f0ad26d7ae84</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<DockerfileContext>..\..</DockerfileContext>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
Now, when you run the project, you’ll see your documentation appear in Swagger:
Conclusion
So, there you have it. Some easy steps to add additional comments/documentation to your ASP.NET 6 Swagger. You can find the code for this reference API here.
Happy Coding!