Swagger/OpenApi模型示例值

3
我正在尝试在我的Swagger/OpenApi中插入自己的值,目前在模型示例值中,我有以下值:

Current situation

所期望的情况如下所示:

enter image description here

我已经研究了它并尝试了多种方法来实现这个目标,例如我尝试添加XML注释,像这样:

first method

然而这并没有起作用。于是我尝试使用MapType函数,它提供了这个功能,我用以下代码实现了这个功能:
c.MapType<Student>(() => new Schema()
                    {
                        example = new Student()
                        {
                            StudentName = "John Doe",
                            Age = 28
                        }
                    });

然而,当我尝试这种方式时,我得到了以下结果: Result 有什么方法可以修复这个问题吗?
2个回答

4

使用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存储库


我认为这是正确的方法,但我似乎无法从Swashbuckle.AspNetCore.Examples导入IExamplesProvider<>类。在插入using Swashbuckle.AspNetCore.Examples之后,我收到错误消息“非泛型类型IExamplesProvider不能与类型参数一起使用”。 - schweppes0x
@schweppes0x 导入 using Swashbuckle.AspNetCore.Filters; 以便能够继承 IExamplesProvider<T> 接口。 - Hassan Monjezi
1
是的,但似乎我的项目不喜欢它。我在另一个项目上尝试了一下,它完美地工作了。不过,我会接受这个答案并让它工作! - schweppes0x
2
接口不是被继承的,而是被实现的。请不要混淆术语。 - Camilo Terevinto
有没有办法将这个功能实现在 MVC 项目中? - schweppes0x

1
我使用的方法解决了我的问题,具体步骤如下:
在Swagger配置中:
.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
                   };
               }
        }
}


这导致了我原始问题中显示的预期值,如图所示。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接