簡體   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