Swagger - how attach an example to particular end-point

I'm working on API where my controllers just returns JsonDocument's instead of DTO's.

I need to provide some response examples for API documentation. But examples should be dedicated for particular end-points.

I've created example provider IExampleProvider<JsonDocument> - and unfortunately the example is populated for all JsonDocument's, instead of the only one decorated by the attribute: [SwaggerResponseExample(200, typeof(MySpecificResponseExample))]

Even if attribute mentioned above is not specified, the example documentation is included.

Startup.cs:

c.ExampleFilters();
c.OperationFilter<AddResponseHeadersFilter>();

services.AddSwaggerExamplesFromAssemblyOf<Startup>();

Example provider:

public class (MySpecificResponseExample))] : IExamplesProvider<JsonDocument>
    {
        public JsonDocument GetExamples()
        {
            return JsonDocument.Parse(@"Example JSON is here.");
        }
    }

Controller:

        [HttpGet]
        [ProducesResponseType(typeof(JsonDocument), 200)]
        [SwaggerResponseExample(200, typeof(MySpecificResponseExample))]
        public async Task<IActionResult> GetSomething() {}

How to include examples to end-points with specific attribute only? I have another end-point where [ProducesResponseType(typeof(JsonDocument), 200)] is specified, but I want to ommit MySpecificResponseExample.


Solution 1:

You can not return JsonDocument over the http since it needs to be converted to json , so I don't see any sense in double parcing and unparcing you better try this and parse to JsonDocument when you get it. But I highly recommend to use JObject Or JArray instead

 public JsonResult GetExamples()
 {
     return new JsonResult( @"Example JSON is here.");
 }