ASP.NET Core 5.0 Web API 自動集成Swashbuckle

ASP.NET Core 5.0 Web API與開放源代碼項目 Swashbuckle.AspNetCore 的維護人員合做,ASP.NET Core API 模板包含對 Swashbuckle 的 NuGet 依賴關係。Swashbuckle 是一個經常使用的開放源代碼 NuGet 包,可動態發出 OpenAPI 文檔。Swashbuckle 經過 API 控制器進行自檢並在運行時或在生成時使用 Swashbuckle CLI 生成 OpenAPI 文檔來實現此目的。web

 

 

 

 

 

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.0" NoWarn="NU1605" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="5.0.0" NoWarn="NU1605" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
  </ItemGroup>

</Project>

  

 

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;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication40
{
    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(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication40", Version = "v1" });
            });
        }

        // 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(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApplication40 v1"));
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

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

  

在 ASP.NET Core 5.0 中,Web API 模板默認啓用 OpenAPI 支持。 若要禁用 OpenAPI,請執行如下操做:json

  • 經過命令行:api

    .NET Core CLIapp

  • dotnet new webapi --no-openapi true
  • 經過 Visual Studio:取消選中「啓用 OpenAPI 支持」。ui

相關文章
相關標籤/搜索