Add response example in SwashBuckle using methods/filters instead of controller attributes

Viewed 12

I have an API which controllers are defined inside another project in a NuGet that I don't have control over, so I can't add attributes to the controller method or classes as it is usually done with SwashBuckle .

I need to add the swagger documentation externally from another project using SwashBuckle API methods, like a custom IDocumentFilter or ISchemaFilter.

The problem comes trying to do the following:

[ProducesResponseType(typeof(MyClass), (int)HttpStatusCode.Accepted)]
public async Task<IActionResult> Get(MyClass request)

I need to do the same but instead of using the method attribute, using SwashBuckle methods, I'm trying using a custom IDocumentFilter with no luck, like so:

public class MyCustomDocFilter : IDocumentFilter
{
  public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
  {
    var pathInfo = swaggerDoc.Paths.FirstOrDefault(p =>...);
    var operationInfo = pathInfo.Value.Operations.First(op => ...);
    var exampleOperationResponse = operationInfo.Value.Responses.First(op => op.Key == "200");
    exampleOperationResponse.Value.Content.Add(MediaTypeNames.Application.Json, new     OpenApiMediaType {
    // Example = new OpenApiString(@"{ ""someProp"": ""someVal""}"),
    Schema = new OpenApiSchema
    {
        Reference = new OpenApiReference
        {
            Id = typeof(MyClass).Name,
            Type = ReferenceType.Schema
        }
    },

  }
}

If I uncomment above's "Example" line, swagger takes it as if the response is a string instead of using the schema for MyClass which is what I need.

0 Answers
Related