0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C#でOpenAPIのタグにコメントを追加する

Posted at

1. はじめに

  • C#でSwaggerUiのタグにコメントを追加したい
  • メソッドなどはXMLコメントで追加できるが、タグだけできないのでなんとかしたい

2. 開発環境

  • C#
  • .NET 6
  • OpenAPI 3.0.0
  • Visual Stduio 2022
  • Swashbuckle.AspNetCore.Annotations (NuGet)

3. Swashbuckle.AspNetCore.Annotationsのインストール

  • NuGetからSwashbuckle.AspNetCore.Annotationsをインストールする
    image.png

  • 適用ボタンをクリックする
    image.png

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. 動作確認

  • SwaggerUiにタグのコメントが表示できた
    image.png

7. 参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?