【问题标题】:SwaggerRequestExample throws error when using a list使用列表时 SwaggerRequestExample 抛出错误
【发布时间】:2017-08-28 18:29:08
【问题描述】:

我已按照 this 教程使用 Swashbuckle 设置自定义 swagger 请求示例,用于 Swagger 帮助页面。

当 API 将单个对象作为主体参数时,它可以正常工作,但是当使用列表时,我得到“对象未设置为对象的实例”异常

这是一个代码示例

using Swashbuckle.Examples;

[HttpPost]
[SwaggerRequestExample(typeof(List<TestModel>), typeof(TestExample))]     
public IHttpActionResult ListTest([FromBody] List<TestModel> tests)
{
    return Ok(tests);
}

public class TestExample : IExamplesProvider
{
    public object GetExamples()
    {
        return new List<TestModel>() {
            new TestModel()
            {
                Id = 1,
                Text = "First object"
            },
            new TestModel()
            {
                Id = 2,
                Text = "Second object"
            },
        };
    }
}

任何帮助将不胜感激

【问题讨论】:

  • @HelderSepu TestModel 只是一个示例模型,它具有两个属性 int Id 和 string Text。我使用的模型要复杂得多,但错误是一样的,所以我认为模型不是问题。 - 如果我删除 SwaggerRequestExample?是的,那么它不会抛出错误。但后来我得到了自动生成的示例请求,这是我不想要的,也是我使用 SwaggerRequestExample 的原因。
  • @HelderSepu 正确,不同的是这是requestexample,而不是responseexample,并且request是一个列表
  • @HelderSepu 是的,正确,唯一的区别是您的请求是单个对象
  • @HelderSepu 看起来是对的,你做了什么不同的事情?

标签: c# asp.net-web-api swagger swashbuckle


【解决方案1】:

@HelderSepu 建议使用 ApplySchemaVendorExtensions,这就是我为使其工作所做的工作:

在我的 SwaggerConfig.cs 中

c.SchemaFilter<ApplySchemaVendorExtensions>();

ApplySchemaVendorExtensions.cs

using Swashbuckle.Swagger;    
public class ApplySchemaVendorExtensions : ISchemaFilter
{
    public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
    {
        if (schema.properties != null)
        {
            if (type == typeof(TestModel))
            {
                schema.example = new TestModel()
                {
                    Id = 1,
                    Text = "Custom text value"
                };
            }
        }
    }
}

如果有人有更好的解决方案,我不会标记为答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    相关资源
    最近更新 更多