Search code examples
c#.netswaggernswagminimal-apis

.NET 8 Minimal API - Finding Endpoints using NSwag that use AddEndpointFilter


I am using currently using AddEndpointFilter for my endpoint using MinimalAPI

app.MapGet("/{Id}", Method).AddEndpointFilter<HeaderFilter>()

Using NSwag's OperationProcessor, I want to be able to get every EndpointFilter that is used in an endpoint. Is there a path within the context I can use? I am currently struggling to find any way of doing this.

public class HeaderOperationProcessor : IOperationProcessor
{
    public bool Process(OperationProcessorContext context)
    {
        // filter need to go here
        var header = new OpenApiParameter()
        {
            Name = "CustomHeader",
            Kind = OpenApiParameterKind.Header,
            IsRequired = true,
            Type = JsonObjectType.String
        };

        context.OperationDescription.Operation.Parameters.Add(header);

        return true;
    }
}

I have tried adding to the metadata of the endpoint and filtering through that, that works to an extent but adds extra lines for an endpoint that may have multiple endpoint filters so it can be quite messy


Solution

  • So the context default type of OperationProcessorContext doesn't include an API description by default but you can declare it as an AspNetCoreOperationProcessorContext which does contain the metadata - E.g.

                var metadata = ((AspNetCoreOperationProcessorContext)context).ApiDescription.ActionDescriptor.EndpointMetadata.Select(m => m.ToString());