Logo

Logo

在 .NET 8 Web API 项目中配置 Swagger 显示描述

Pastore Antonio
Pastore Antonio 2025年09月08日
426 阅读 0 评论 约 6940 字 阅读约 14 分钟

在 .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 描述信息,包括方法说明、参数描述、返回值说明和示例等。

查看完整代码

橙子主题打折出售

其实我不卖,主要是这里是放广告的,所以就放了一个
毕竟主题都没做完,卖了也是坑.

购买它
部分文章可能存在转载,如果涉及到侵权,请联系删除文章。

留言板

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

6 + 1 = ?

探索AIGC相关的精彩内容,共 15 篇文章

Azure AI 服务之语音识别

简介 Azure AI 服务中的语音识别 API 是微软提供的一项先进技术,旨在帮助开发者轻松实现语 ... 在 .NET 8 Web API 项目中配置 Swagger 显示描述

2026-02-17 · Xzavier Aaron
MCP | 一文详解什么是 MCP以及 MCP 可以做什么

一、什么是 MCP MCP(Model Context Protocol)是一个专为大型语言模型(L ... 在 .NET 8 Web API 项目中配置 Swagger 显示描述

2026-02-14 · Shen, Luke
你的工作流程,值得一个“全自动数字分身”:录制、截图、成文,一气呵成

一、一句话认识 TestFlow Recorder 在数字化工作环境中,如何准确记录操作步骤并生成清 ... 在 .NET 8 Web API 项目中配置 Swagger 显示描述

2026-02-14 · Xzavier Aaron
Flowise 前端框架配置指南

用户需求 问题:有没有适合配置 Flowise 的前端框架? 目标:寻找类似 Open WebUI ... 在 .NET 8 Web API 项目中配置 Swagger 显示描述

2026-02-14 · Xzavier Aaron