【问题标题】:Swagger/OpenApi Model Example ValueSwagger/OpenApi 模型示例值
【发布时间】:2022-01-16 17:46:05
【问题描述】:

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

想要的情况如下图:

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

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

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

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

有什么办法解决这个问题?

【问题讨论】:

    标签: c# .net swagger


    【解决方案1】:

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

    添加您的默认模型(您打算以 swagger 显示的默认值)如下:

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

    注意它正在实现IExamplesProvider&lt;StudentDto&gt;,其中StudentDto 是我发送到API 控制器的主要模型。

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

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

    更多信息和示例,请访问该项目的GitHub Repository

    【讨论】:

    • 我认为这是要走的路,但是我似乎无法从 Swashbuckle.AspNetCore.Examples 导入 IExamplesProvider 类。插入 using Swashbuckle.AspNetCore.Examples 后出现错误“非泛型类型 IExamplesProvider 不能与类型参数一起使用”
    • @schweppes0x 导入using Swashbuckle.AspNetCore.Filters; 以便能够从IExamplesProvider&lt;T&gt; 接口继承。
    • 是的,但我的项目似乎不喜欢它。我尝试了另一个项目,效果很好。但是我会接受这个答案!
    • 接口不是继承的,而是实现的。请不要混淆术语
    • 有没有办法在 MVC 项目中实现这一点?
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 2020-03-14
      • 2015-05-08
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多