简体   繁体   中英

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:

现在的情况

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:

第一种方法

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:

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:

Add your default model (the default value which you intend to be shown in swagger) as follow:

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.

And this is how we should apply it for our controller action:

    [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:

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

and then within 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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