第十一章 API文档和Swagger

11.1 Swagger/OpenAPI基础

什么是Swagger

Swagger(现在称为OpenAPI)是一套用于描述REST API的规范。它提供了一种标准化的方式来记录API,包括端点、请求/响应模型、认证方法等。

配置Swagger

// 在Program.cs中
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo 
    { 
        Title = "Todo API", 
        Version = "v1",
        Description = "一个简单的待办事项API",
        Contact = new OpenApiContact
        {
            Name = "Your Name",
            Email = "your.email@example.com",
            Url = new Uri("https://yourwebsite.com")
        }
    });

    // 包含XML注释
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath);

    // JWT认证配置
    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中间件
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Todo API V1");
        c.RoutePrefix = string.Empty; // 设置Swagger UI在应用根目录
    });
}

11.2 文档化API

使用XML注释

首先在项目文件中启用XML文档生成:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
    <NoWarn>$(NoWarn);1591</NoWarn>
  </PropertyGroup>
</Project>

然后在控制器方法上添加XML注释:

/// <summary>
/// 获取所有待办事项
/// </summary>
/// <returns>待办事项列表</returns>
/// <response code="200">成功返回待办事项列表</response>
/// <response code="500">内部服务器错误</response>
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<TodoItem>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems()
{
    return await _repository.GetAllAsync();
}

/// <summary>
/// 根据ID获取特定的待办事项
/// </summary>
/// <param name="id">待办事项的唯一标识符</param>
/// <returns>指定的待办事项</returns>
/// <response code="200">成功返回待办事项</response>
/// <response code="404">未找到指定的待办事项</response>
[HttpGet("{id}")]
[ProducesResponseType(typeof(TodoItem), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<TodoItem>> GetTodoItem(long id)
{
    var todoItem = await _repository.GetByIdAsync(id);

    if (todoItem == null)
    {
        return NotFound();
    }

    return todoItem;
}

/// <summary>
/// 创建新的待办事项
/// </summary>
/// <param name="todoItem">要创建的待办事项</param>
/// <returns>创建的待办事项</returns>
/// <response code="201">成功创建待办事项</response>
/// <response code="400">请求数据无效</response>
[HttpPost]
[ProducesResponseType(typeof(TodoItem), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<TodoItem>> CreateTodoItem(TodoItem todoItem)
{
    var createdItem = await _repository.AddAsync(todoItem);

    return CreatedAtAction(nameof(GetTodoItem), 
        new { id = createdItem.Id }, createdItem);
}

wechat_2025-07-31_105805_938


posted @ 2025-08-07 09:11  高宏顺  阅读(280)  评论(0)    收藏  举报