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

.NET Core 6:如何为SwaggerUI提供自定义请求示例?

在.NET Core 6中给Swagger定义具体请求示例的方法

当然可以通过C#代码为Swagger UI定义更具体的请求示例,以下是几种实用方案:

方案1:使用Swashbuckle.AspNetCore.Filters包的示例特性

这是最灵活的方式,适合复杂模型的示例定义:

  1. 安装NuGet包:Swashbuckle.AspNetCore.Filters
  2. 创建示例提供类,实现IExamplesProvider<T>接口:
public class EditorUpdateMaterialCalculationRequestExample : IExamplesProvider<EditorUpdateMaterialCalculationConfigurationRequest>
{
    public EditorUpdateMaterialCalculationConfigurationRequest GetExamples()
    {
        return new EditorUpdateMaterialCalculationConfigurationRequest
        {
            MaterialId = "MAT-001",
            MaterialType = "RawMaterial",
            // 补充其他属性的具体示例值
        };
    }
}
  1. 在Controller方法的参数上添加[SwaggerRequestExample]特性:
[HttpPost]
[Route(nameof(UpdateMaterialCalculationConfiguration))]
[ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(EditorResponse<EditorMaterialCalculationConfigurationResponse>))]
public IActionResult UpdateMaterialCalculationConfiguration(
    [Required][FromBody]
    [SwaggerRequestExample(typeof(EditorUpdateMaterialCalculationConfigurationRequest), typeof(EditorUpdateMaterialCalculationRequestExample))]
    EditorUpdateMaterialCalculationConfigurationRequest request)
{
    ...
}
  1. 在Program.cs中启用示例过滤器:
builder.Services.AddSwaggerGen(c =>
{
    // 其他Swagger配置
    c.ExampleFilters();
});

方案2:使用.NET自带的[Example]特性(.NET 6+ 兼容)

适合简单模型,直接在属性上标记示例值:

  1. 在请求模型的属性上添加[Example]特性:
public class EditorUpdateMaterialCalculationConfigurationRequest
{
    [Example("MAT-001")]
    public string MaterialId { get; set; }

    [Example("RawMaterial")]
    public string MaterialType { get; set; }

    // 其他属性
}
  1. 在Program.cs的Swagger配置中启用注释和示例支持:
builder.Services.AddSwaggerGen(c =>
{
    // 其他Swagger配置
    c.EnableAnnotations();
    // 可选:启用XML注释(需在项目属性中勾选生成XML文档文件)
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath);
});

方案3:自定义Swagger Schema过滤器

适合全局或批量配置示例的场景:

  1. 创建自定义Schema过滤器:
public class RequestExampleSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (context.Type == typeof(EditorUpdateMaterialCalculationConfigurationRequest))
        {
            schema.Example = new OpenApiObject
            {
                ["MaterialId"] = new OpenApiString("MAT-001"),
                ["MaterialType"] = new OpenApiString("RawMaterial"),
                // 补充其他属性示例
            };
        }
    }
}
  1. 在Program.cs中注册过滤器:
builder.Services.AddSwaggerGen(c =>
{
    // 其他Swagger配置
    c.SchemaFilter<RequestExampleSchemaFilter>();
});

内容的提问来源于stack exchange,提问作者Dee J. Doena

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 22:25:23