Logo

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

photo

2025年09月08日

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

橙子主题打折出售

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

购买它
所有附件
该文章没有附件.
本文为原创文章,请注意保留出处!

留言板

发表回复

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

场景描述假设你有一个带有滚动条的div容器,你希望用户可以通过拖动鼠标来滚动内容,而不是直接滚动滚动...在DIV中实现拖动滚动功能

热门文章

无法握住的故土 在我们心灵最温暖的角落,总有一寸土地是属于故乡的。虽然我们看似已远离故土,可骨子里对故乡的依恋却是从未冷却过。我们无论漂泊他乡,还是在繁华都市平步青云,可故乡的悠悠情思总会潜入梦乡与你缠绵。是儿时那一缕缕茉莉的清香萦绕在梦境,也是邻家那已锈迹斑斑的铁壶里,开出艳丽的花儿在梦的边缘摇曳。故土就这样根深蒂固地在我们的灵魂深处烙下深深的印记。 作者:Pastore Antonio
1596 浏览量
EWS(Exchange Service)基本使用(获取个人会议,会议室会议内容,会议室列表,发送会议,修改会议,删除会议) 最近公司要求和exchange服务对接,所以稍微研究了一下官方文档,做出以下总结,欢迎大家补充。先...EWS(ExchangeService)基本使用(获取个人会议,会议室会议内容,会议室列表,发送会议,修改会议,删除会议) 作者:Pastore Antonio
1585 浏览量
Sql Server 部署SSIS包完成远程数据传输 本篇介绍如何使用SSIS和作业完成自动更新目标数据任务。**温馨提示:如需转载本文,请注明...SqlServer部署SSIS包完成远程数据传输 作者:Pastore Antonio
1578 浏览量
SQL Server AG集群启动不起来的临时自救大招 背景前晚一朋友遇到AG集群发生来回切换不稳定的情况,情急之下,朋友在命令行使用命令重启WSFC集群...SQLServerAG集群启动不起来的临时自救大招 作者:Pastore Antonio
1572 浏览量
windows 下安装 memcahce 官网上并未提供Memcached的Windows平台安装包,我们可以使用以下链接来下载,你需...windows下安装memcahce 作者:Pastore Antonio
1566 浏览量