SwaggerRequestExample 在使用列表时抛出错误
SwaggerRequestExample throws error when using a list
我已按照 this 教程使用 Swashbuckle 为 Swagger 帮助页面设置自定义 swagger 请求示例。
当 API 将单个对象作为正文参数时它工作正常,但是当使用列表时我得到一个 "Object not set to an instance of an object" 异常
这是一个代码示例
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 建议使用 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"
};
}
}
}
}
如果有人有更好的解决方案,我不会标记为答案。
我已按照 this 教程使用 Swashbuckle 为 Swagger 帮助页面设置自定义 swagger 请求示例。
当 API 将单个对象作为正文参数时它工作正常,但是当使用列表时我得到一个 "Object not set to an instance of an object" 异常
这是一个代码示例
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 建议使用 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"
};
}
}
}
}
如果有人有更好的解决方案,我不会标记为答案。