繁体   English   中英

Swagger/OpenApi Model 示例值

[英]Swagger/OpenApi Model Example Value

我试图在我的 Swagger/OpenApi 中插入我自己的值,目前在 Model 示例值中我有以下值:

现在的情况

期望的情况如下图所示:

在此处输入图像描述

我研究了它并尝试了多种方法来实现这一点,例如我尝试像这样添加 XMLComments:

第一种方法

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

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

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

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

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

添加您的默认 model (您打算以大摇大摆的方式显示的默认值)如下:

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

请注意,它是从IExamplesProvider<StudentDto>继承的,其中StudentDto是主要的 model,我将其发送到 API controller。

这就是我们应该如何将它应用于我们的 controller 操作:

    [SwaggerRequestExample(typeof(StudentDto), typeof(StudentDtoDefault))]
    [HttpPost]
    public ActionResult Post([FromBody] StudentDto student)
    {
        ...
    }

在此处输入代码

我使用并解决了我的问题的方法如下:

在 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
                   };
               }
        }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM