写在前面
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。 本文记录如何配置基于Swagger 的 ASP.NET Core 应用程序的 OpenAPI 规范。
需要从NuGet 安装 Swashbuckle.AspNetCore 包
代码实现
var builder = WebApplication.CreateBuilder(args);builder.Services.AddControllers();builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{c.SwaggerDoc("v1", new(){Title = builder.Environment.ApplicationName,Version = "v1"});
});var app = builder.Build();if (app.Environment.IsDevelopment())
{app.UseSwagger();app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json",$"{builder.Environment.ApplicationName} v1"));
}app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.MapGet("/swag", () => "Hello Swagger!");
app.MapGet("/skipme", () => "Skipping Swagger.").ExcludeFromDescription();app.Run();
运行示例