使用NuGet包Swashbuckle.AspNetCore.Filters
进行如下操作:
按照以下方式添加您的默认模型(您希望在 Swagger 中显示的默认值):
public class StudentDtoDefault : IExamplesProvider<StudentDto>
{
public StudentDto GetExamples()
{
return new StudentDto
{
StudentName = "John Doe",
Age = 28
};
}
}
请注意,它正在实现 IExamplesProvider<StudentDto>
,其中StudentDto
是我要发送到API控制器的主要模型。
下面是我们在控制器操作中应该如何应用:
[SwaggerRequestExample(typeof(StudentDto), typeof(StudentDtoDefault))]
[HttpPost]
public ActionResult Post([FromBody] StudentDto student)
{
...
}
了解更多信息和示例,请访问此项目的GitHub存储库。
.EnableSwagger("/swagger", c=> {
c.SchemaFilter<SwaggerExamples>();
})
然后在SwaggerExamples.cs文件中:
using Swashbuckle.Swagger;
public class SwaggerExamples : ISchemaFilter
{
public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
{
if(type == typeof(Student))
{
schema.example = new Student
{
StudentName = "John",
Age = 28
};
}
}
}
using Swashbuckle.AspNetCore.Examples
之后,我收到错误消息“非泛型类型IExamplesProvider不能与类型参数一起使用”。 - schweppes0xusing Swashbuckle.AspNetCore.Filters;
以便能够继承IExamplesProvider<T>
接口。 - Hassan Monjezi