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

ASP.NET Core Minimal API中OpenAPI requestBody示例设置报错及解决

问题分析与解决

问题根源

你代码中的错误在于:将序列化后的JSON字符串用OpenApiString直接赋值给Example属性,但OpenAPI规范要求Example必须是结构化的OpenApiAny对象,而非纯字符串。Swagger-UI在解析时无法将字符串转换为可渲染的JS对象,因此抛出了Cannot read properties of undefined (reading 'toJS')的错误。

正确实现方案

方案一:用OpenApiAnyFactory转换对象为兼容结构

直接将实例序列化为JSON后,通过OpenApiAnyFactory转换成OpenAPI能识别的结构:

.WithOpenApi(x =>
{
    var testSample = new TestClass();
    var sampleJson = JsonSerializer.Serialize(testSample);
    var openApiExample = OpenApiAnyFactory.CreateFromJson(sampleJson);

    x.RequestBody = new OpenApiRequestBody
    {
        Content = new Dictionary<string, OpenApiMediaType>
        {
            ["application/json"] = new OpenApiMediaType
            {
                Example = openApiExample
            }
        }
    };
    return x;
})

方案二:结合SchemaGenerator生成带示例的Schema

如果你的TestClass已经被Swagger的Schema生成器识别,可以直接生成对应的Schema并绑定示例:

.WithOpenApi((x, context) =>
{
    var testSample = new TestClass();
    var schema = context.SchemaGenerator.GenerateSchema(typeof(TestClass), context.SchemaRepository);
    schema.Example = OpenApiAnyFactory.CreateFromJson(JsonSerializer.Serialize(testSample));

    x.RequestBody = new OpenApiRequestBody
    {
        Content = new Dictionary<string, OpenApiMediaType>
        {
            ["application/json"] = new OpenApiMediaType
            {
                Schema = schema
            }
        }
    };
    return x;
})

额外简化方案(非动态场景)

如果不需要动态构建示例,直接在TestClass上添加特性更省心:

  • 安装Swashbuckle.AspNetCore.Filters包后,给类加[SwaggerExample(typeof(TestClass))]特性
  • 或者在类的属性上单独加[Example("示例值")]特性,Swagger会自动渲染示例内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 06:54:58