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 文档来实现此目的。



  <PropertyGroup>

net5.0

  </PropertyGroup>

  <ItemGroup>

  </ItemGroup>

</Project>

usingMicrosoft.AspNetCore.Builder;

usingMicrosoft.AspNetCore.Hosting;

usingMicrosoft.AspNetCore.HttpsPolicy;

usingMicrosoft.AspNetCore.Mvc;

usingMicrosoft.Extensions.Configuration;

usingMicrosoft.Extensions.DependencyInjection;

usingMicrosoft.Extensions.Hosting;

usingMicrosoft.Extensions.Logging;

usingMicrosoft.OpenApi.Models;

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Threading.Tasks;

namespaceWebApplication40

{

publicclassStartup

    {

publicStartup(IConfiguration configuration)

        {

            Configuration = configuration;

        }

publicIConfiguration Configuration {get; }

// This method gets called by the runtime. Use this method to add services to the container.

publicvoidConfigureServices(IServiceCollection services)

        {

            services.AddControllers();

            services.AddSwaggerGen(c =>

            {

c.SwaggerDoc("v1",newOpenApiInfo { Title ="WebApplication40", Version ="v1"});

            });

        }

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

publicvoidConfigure(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,请执行以下操作:

通过命令行:

.NET Core CLI

dotnet new webapi --no-openapi true

通过 Visual Studio:取消选中“启用 OpenAPI 支持”。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容