简体   繁体   English

Swagger/OpenApi Model 示例值

[英]Swagger/OpenApi Model Example Value

I am trying to insert my own values within my Swagger/OpenApi, currently in the Model Example Value I have the following values:我试图在我的 Swagger/OpenApi 中插入我自己的值,目前在 Model 示例值中我有以下值:

现在的情况

The desired situation is as shown below:期望的情况如下图所示:

在此处输入图像描述

I've looked into it and tried multiple methods to achive this, for example I tried adding XMLComments like this:我研究了它并尝试了多种方法来实现这一点,例如我尝试像这样添加 XMLComments:

第一种方法

However this does not work.但是,这不起作用。 Then I tried to use the MapType function which provides this functionality, I've done this with the following code:然后我尝试使用提供此功能的 MapType function,我使用以下代码完成了此操作:

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

However, when I try it this way, I get the following result:但是,当我以这种方式尝试时,我得到以下结果: 结果

Any way to fix this?有任何解决这个问题的方法吗?

Use NuGet Package Swashbuckle.AspNetCore.Filters as follow:使用 NuGet Package Swashbuckle.AspNetCore.Filters如下:

Add your default model (the default value which you intend to be shown in swagger) as follow:添加您的默认 model (您打算以大摇大摆的方式显示的默认值)如下:

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

Note it is inheriting from IExamplesProvider<StudentDto> which StudentDto is the main model which I'm sending to the API controller.请注意,它是从IExamplesProvider<StudentDto>继承的,其中StudentDto是主要的 model,我将其发送到 API controller。

And this is how we should apply it for our controller action:这就是我们应该如何将它应用于我们的 controller 操作:

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

enter code here在此处输入代码

The method I used and which resolved my issue was the following:我使用并解决了我的问题的方法如下:

Within the Swagger configuration:在 Swagger 配置中:

.EnableSwagger("/swagger", c=> {
    c.SchemaFilter<SwaggerExamples>();
})

and then within SwaggerExamples.cs:然后在 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
                   };
               }
        }
}

This resulted in the expected values shown in the image in my original question.这导致了我原始问题中图像中显示的预期值。

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

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