You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Swagger自动生成的C# Record定义example属性?

在C# Record中定义Swagger自定义示例

要在C# Record的字段上设置Swagger的自定义示例,替代默认的"string",有两种常用方案,直接在.cs文件中配置即可:

方案1:使用XML注释的<example>标签

Swashbuckle(Visual Studio自动生成Swagger依赖的库)支持读取代码的XML注释中的<example>标签来生成示例值。

步骤:

  1. 开启项目XML文档生成
    右键你的项目 → 属性 → 生成 → 勾选「XML文档文件」,可以保留默认路径(比如bin\Debug\net6.0\YourProject.xml)。

  2. 在Record中添加带<example>的注释

public record Foo(
    /// <summary>
    /// Bar字段的描述(可选)
    /// </summary>
    /// <example>a custom string example here</example>
    string Bar
);
  1. 配置Swashbuckle读取XML注释
    在Program.cs的Swagger配置中添加读取XML文件的代码:
using System.Reflection;

var builder = WebApplication.CreateBuilder(args);

// 其他服务配置...

builder.Services.AddSwaggerGen(c =>
{
    var xmlFileName = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlFilePath = Path.Combine(AppContext.BaseDirectory, xmlFileName);
    // 读取XML注释
    c.IncludeXmlComments(xmlFilePath);
});

var app = builder.Build();

// 其他中间件配置...

方案2:使用[SwaggerSchema]注解

这种方式更直接,无需依赖XML注释,需要先安装Swashbuckle的注解包。

步骤:

  1. 安装NuGet包
    在NuGet包管理器中搜索并安装Swashbuckle.AspNetCore.Annotations。

  2. 在Record字段上添加注解

using Swashbuckle.AspNetCore.Annotations;

public record Foo(
    [SwaggerSchema(Example = "a custom string example here")]
    string Bar
);
  1. 启用Swagger注解支持
    在Program.cs的Swagger配置中启用注解:
builder.Services.AddSwaggerGen(c =>
{
    // 启用Swagger注解
    c.EnableAnnotations();
});

两种方案都能实现你想要的效果:启动应用后,Swagger中Bar字段的示例值会显示为你自定义的字符串,而不是默认的"string"。

内容的提问来源于stack exchange,提问作者AoooR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 14:25:33