VSCODE ASP.NET Coreで「Swagger」を導入して利用するまで

VSCODE ASP.NET Coreで「Swagger」を導入して利用するまで

VSCODEで「Swagger」を導入して利用するまでの手順を記述してます。

環境

  • OS windows10 pro 64bit
  • VSCODE 1.56.2
  • .NET Core 3.1.409

nugetを使用

まずは、vscodeで「nuget」を使用できるようにします。

Swaggerインストール

「F1」キーを押下して「NuGet Package Manager: Add Package」を選択します。

「Swashbuckle.AspNetCore」を選択します。

バージョンを選択します。ここでは最新バージョンである「6.1.4」を選択してます。

正常にインストールが終われば、右下に下図が通知されると思います。

「csproj」ファイルを確認すると「Swashbuckle.AspNetCore」が追加されていることが確認できます。

Swagger利用

「Startup.cs」を以下のように編集します。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
// 追加
using Microsoft.OpenApi.Models;

namespace testapi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            // 追加
            services.AddSwaggerGen(s =>
            {
                s.SwaggerDoc("v1.0.0", new OpenApiInfo { Title = "SwaggerTest", Version = "v1.0.0" });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                // 追加(デバック時のみ実行)
                app.UseSwagger();
                app.UseSwaggerUI(s => s.SwaggerEndpoint("/swagger/v1.0.0/swagger.json", "SwaggerTest v1.0.0"));
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

起動してブラウザから「https://localhost:5001/swagger/」にアクセスすると以下の画面が表示されます。