如何为Swagger自动生成的C# Record定义example属性?
在C# Record中定义Swagger自定义示例
要在C# Record的字段上设置Swagger的自定义示例,替代默认的"string",有两种常用方案,直接在.cs文件中配置即可:
方案1:使用XML注释的<example>标签
Swashbuckle(Visual Studio自动生成Swagger依赖的库)支持读取代码的XML注释中的<example>标签来生成示例值。
步骤:
开启项目XML文档生成
右键你的项目 → 属性 → 生成 → 勾选「XML文档文件」,可以保留默认路径(比如bin\Debug\net6.0\YourProject.xml)。在Record中添加带
<example>的注释
public record Foo( /// <summary> /// Bar字段的描述(可选) /// </summary> /// <example>a custom string example here</example> string Bar );
- 配置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的注解包。
步骤:
安装NuGet包
在NuGet包管理器中搜索并安装Swashbuckle.AspNetCore.Annotations。在Record字段上添加注解
using Swashbuckle.AspNetCore.Annotations; public record Foo( [SwaggerSchema(Example = "a custom string example here")] string Bar );
- 启用Swagger注解支持
在Program.cs的Swagger配置中启用注解:
builder.Services.AddSwaggerGen(c => { // 启用Swagger注解 c.EnableAnnotations(); });
两种方案都能实现你想要的效果:启动应用后,Swagger中Bar字段的示例值会显示为你自定义的字符串,而不是默认的"string"。
内容的提问来源于stack exchange,提问作者AoooR
相关产品推荐
相关产品推荐

