using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;
var builder = WebApplication.CreateBuilder(args);
// 添加Swagger服务
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
// 确保XML注释文件与项目文件中的路径一致
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "ToDoList API",
Version = "v1",
Description = "一个简单的ToDoList API示例",
Contact = new OpenApiContact() { Name = "开发者", Email = "developer@example.com" }
});
// 添加全局过滤器,过滤掉不需要显示的API
options.DocumentFilter<IgnoreObsoleteActionFilter>();
});
var app = builder.Build();
// 启用中间件用于生成Swagger作为JSON endpoint
app.UseSwagger();
// 启用中间件用于提供swagger-ui (HTML, JS, CSS等)
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "ToDoList API V1");
options.RoutePrefix = string.Empty; // 设置为空,则可通过根路径访问Swagger UI
});
app.MapGet("/", () => "Hello World!");
app.Run();
这段代码示例展示了如何在.NET 6的Web API项目中集成Swagger以生成API文档,并提供了一个简单的中间件来过滤掉不需要显示的API。这是一个实际的开发场景,能够帮助开发者在实际项目中快速集成和使用Swagger。