Swagger/OpenApi 模型示例值

sch*_*s0x 3 .net c# swagger

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

现在的情况

期望的情况如下图:

在此输入图像描述

我研究过它并尝试了多种方法来实现此目的,例如我尝试添加如下 XMLComments:

第一种方法

然而这不起作用。然后我尝试使用提供此功能的 MapType 函数,我使用以下代码完成了此操作:

c.MapType<Student>(() => new Schema()
                    {
                        example = new Student()
                        {
                            StudentName = "John Doe",
                            Age = 28
                        }
                    });
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试这种方式时,我得到以下结果: 结果

有任何解决这个问题的方法吗 ?

Has*_*ezi 5

使用 NuGet 包Swashbuckle.AspNetCore.Filters如下:

添加您的默认模型(您打算在 swagger 中显示的默认值),如下所示:

public class StudentDtoDefault : IExamplesProvider<StudentDto>
{
   public StudentDto GetExamples()
    {
        return new StudentDto
        {
             StudentName = "John Doe",
             Age = 28
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,它正在实现IExamplesProvider<StudentDto>StudentDto发送到 API 控制器的主要模型。

这就是我们应该如何将其应用到我们的控制器操作中:

[SwaggerRequestExample(typeof(StudentDto), typeof(StudentDtoDefault))]
[HttpPost]
public ActionResult Post([FromBody] StudentDto student)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息和示例,请访问该项目的GitHub 存储库

  • 接口不是继承的,而是实现的。请不要混淆术语 (2认同)