在 .NET 8 Web API 项目中配置 Swagger 显示描述,你可以通过以下几种方式:
1. 基本 Swagger 配置
首先在 Program.cs
中配置 Swagger:
var builder = WebApplication.CreateBuilder(args);
// 添加服务
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "我的 API",
Description = "这是一个示例 Web API",
Contact = new OpenApiContact
{
Name = "开发者",
Email = "developer@example.com"
}
});
});
var app = builder.Build();
// 配置管道
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "我的 API V1");
c.RoutePrefix = string.Empty; // 设置 Swagger UI 为根路径
});
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
2. 使用 XML 文档注释
启用 XML 文档生成
在项目文件 (.csproj
) 中添加:
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
配置 Swagger 读取 XML 文档
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "我的 API",
Description = "这是一个示例 Web API"
});
// 包含 XML 文档
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
3. 在控制器和方法中添加描述
/// <summary>
/// 用户管理控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Produces("application/json")]
public class UsersController : ControllerBase
{
/// <summary>
/// 获取所有用户
/// </summary>
/// <remarks>
/// 返回系统中所有用户的列表
///
/// 示例请求:
///
/// GET /api/users
///
/// </remarks>
/// <returns>用户列表</returns>
/// <response code="200">成功返回用户列表</response>
/// <response code="404">未找到用户</response>
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<User>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<IEnumerable<User>>> GetUsers()
{
// 实现逻辑
}
/// <summary>
/// 根据 ID 获取用户
/// </summary>
/// <param name="id">用户 ID</param>
/// <returns>指定的用户信息</returns>
/// <response code="200">成功返回用户信息</response>
/// <response code="404">用户不存在</response>
[HttpGet("{id}")]
[ProducesResponseType(typeof(User), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<User>> GetUser(int id)
{
// 实现逻辑
}
/// <summary>
/// 创建新用户
/// </summary>
/// <param name="user">用户信息</param>
/// <returns>创建的用户</returns>
/// <response code="201">用户创建成功</response>
/// <response code="400">请求参数无效</response>
[HttpPost]
[ProducesResponseType(typeof(User), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<User>> CreateUser([FromBody] CreateUserRequest user)
{
// 实现逻辑
}
}
4. 为模型添加描述
/// <summary>
/// 用户信息
/// </summary>
public class User
{
/// <summary>
/// 用户 ID
/// </summary>
/// <example>1</example>
public int Id { get; set; }
/// <summary>
/// 用户名
/// </summary>
/// <example>zhangsan</example>
[Required]
[StringLength(50)]
public string UserName { get; set; }
/// <summary>
/// 电子邮箱
/// </summary>
/// <example>zhangsan@example.com</example>
[Required]
[EmailAddress]
public string Email { get; set; }
/// <summary>
/// 创建时间
/// </summary>
/// <example>2024-01-01T00:00:00Z</example>
public DateTime CreatedAt { get; set; }
}
/// <summary>
/// 创建用户请求
/// </summary>
public class CreateUserRequest
{
/// <summary>
/// 用户名(必填)
/// </summary>
/// <example>zhangsan</example>
[Required(ErrorMessage = "用户名不能为空")]
[StringLength(50, ErrorMessage = "用户名长度不能超过50个字符")]
public string UserName { get; set; }
/// <summary>
/// 电子邮箱(必填)
/// </summary>
/// <example>zhangsan@example.com</example>
[Required(ErrorMessage = "邮箱不能为空")]
[EmailAddress(ErrorMessage = "邮箱格式不正确")]
public string Email { get; set; }
}
5. 使用特性添加更多描述
[HttpGet]
[SwaggerOperation(
Summary = "获取用户列表",
Description = "获取系统中所有用户的详细信息列表",
Tags = new[] { "用户管理" }
)]
[SwaggerResponse(200, "成功", typeof(IEnumerable<User>))]
[SwaggerResponse(404, "未找到数据")]
public async Task<ActionResult<IEnumerable<User>>> GetUsers()
{
// 实现逻辑
}
6. 高级配置
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "我的 API",
Description = "这是一个功能完整的 Web API",
TermsOfService = new Uri("https://example.com/terms"),
Contact = new OpenApiContact
{
Name = "技术支持",
Email = "support@example.com",
Url = new Uri("https://example.com/contact")
},
License = new OpenApiLicense
{
Name = "MIT License",
Url = new Uri("https://opensource.org/licenses/MIT")
}
});
// 包含 XML 注释
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
// 支持多个 XML 文件(如果有引用的项目)
// c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "OtherProject.xml"));
// 配置授权
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
});
这样配置后,你的 Swagger UI 将显示完整的 API 描述信息,包括方法说明、参数描述、返回值说明和示例等。