Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`SwaggerRequestExample` is being ignored

As I was adding swagger to my API, I wanted to get default values and response examples. I added the NuGet packages and tried to follow this tutorial. The SwaggerResponseExample attribute works properly but the SwaggerRequestExample seems to be simply ignored.

With my action defined as follow

[SwaggerRequestExample(typeof(int), typeof(PersonExamples.Request))]
[SwaggerResponseExample(200, typeof(PersonExamples.Response))]
/* more attribute & stuff */
public IActionResult Get(int id) { /* blabla */ }

The PersonExamples class being defined as follow (non-revelant code removed)

public class PersonExamples
{
    public class Request : IExamplesProvider
    {
        public object GetExamples() { return _persons.List().First().Id; }
    }

    public class Response : IExamplesProvider
    {
        public object GetExamples() { return _persons.List().First(); }
    }
}

Here is also the relevant part of the Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(conf =>
    {
        conf.SwaggerDoc(_documentationPrefix, new Info
        {
            Title = "Global",
            Version = "v0",
        });

        conf.OperationFilter<ExamplesOperationFilter>();

        var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "Global.xml");
        conf.IncludeXmlComments(filePath);
    });

}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseSwagger(opt =>
    {
        opt.RouteTemplate = "{documentName}/swagger.json";
    });

    if (env.IsDevelopment())
    {
        app.UseSwaggerUI(conf =>
        {
            conf.SwaggerEndpoint($"/{_documentationPrefix}/swagger.json", "DataService API");
            conf.RoutePrefix = "doc/swagger";
        });
    }
}

When I run my project and go to the swagger.json page I notice that the response example is properly written, but the request example is nowhere to be found. After further debugging, I notice that a breakpoint placed in PersonExamples.Response.GetExamples will be hit when the page is called, but one placed in the PersonExamples.Request.GetExamples method won't. So i believe that the SwaggerRequestExample attribute never calls the method and may not even be called itself.

Did I improperly used the tag ? Why is it never called ?

like image 878
Mathieu VIALES Avatar asked Oct 29 '22 00:10

Mathieu VIALES


1 Answers

I know this question is quite old, but Swagger Examples don't support GET request parameters (query parameters). It only works when the parameters are in the request body (eg: POST requests)

like image 195
Champika Samarasinghe Avatar answered Dec 04 '22 05:12

Champika Samarasinghe