Home > Net >  Swagger/OpenApi Model Example Value
Swagger/OpenApi Model Example Value

Time:12-14

I am trying to insert my own values within my Swagger/OpenApi, currently in the Model Example Value I have the following values:

Current situation

The desired situation is as shown below :

enter image description here

I've looked into it and tried multiple methods to achive this, for example I tried adding XMLComments like this:

first method

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

Any way to fix this ?

CodePudding user response:

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 implementing IExamplesProvider<StudentDto> where 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)
{
    ...
}

For more information and example, please visit the GitHub Repository of this project.

  • Related