1. はじめに
- C#でSwaggerUiのタグにコメントを追加したい
- メソッドなどはXMLコメントで追加できるが、タグだけできないのでなんとかしたい
2. 開発環境
- C#
- .NET 6
- OpenAPI 3.0.0
- Visual Stduio 2022
- Swashbuckle.AspNetCore.Annotations (NuGet)
3. Swashbuckle.AspNetCore.Annotationsのインストール
4. Program.csの修正
-
options.EnableAnnotations();
の1行を追加する
Program.cs
using System.Reflection;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
// builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGen(options =>
{
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
// EnabeAnnotationsを追加する
options.EnableAnnotations();
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Sample APIs");
});
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
5. Controllerの修正
- ControllerにSwaggerTagのアノテーションを追加して、コメントを入力する
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
namespace WebApplication1.Controllers
{
/// <summary>
/// WeatherForecastController XMLコメント
/// </summary>
[ApiController]
[Route("[controller]")]
[SwaggerTag("Tag Comment")]
public class WeatherForecastController : ControllerBase
{
6. 動作確認
7. 参考文献