NSwag : How can i suppress controllers ASP.NET Core
Asked Answered
C

2

0

ASP.NEt Core 3.1 I would like to suppress one certain controller. Therefore i tried use the DocumentProcessor, but without success.

public class DocumentProcessor : IDocumentProcessor

I have no access to this specific controller. So i need a solution like ist was possible before. It was possible in ASP.NET MVC by "filtering" the controllers.

old code:

var controllers = new[] { typeof(ExternalApiController)
                                        , typeof(ExternalApiDatasourceController)                                        
                                    };

var document = Task.Run(async () => await generator.GenerateForControllersAsync(controllers)).GetAwaiter().GetResult();
Cache answered 7/5, 2020 at 8:6 Comment(0)
C
1

I think the best option is to implement and register a custom operation process and exclude all operations of this controller (return false): https://github.com/RicoSuter/NSwag/wiki/Document-Processors-and-Operation-Processors#operation-processors

Chewning answered 30/9, 2020 at 20:20 Comment(0)
T
1

To make Rico's answer concrete, here's how to do it in your scenario. Let's say you want to exclude your ExternalApiController and related schema from showing up in Swagger. You would first create a custom document post-processor for NSwag, like this:

using NSwag.Generation.AspNetCore;
using NSwag.Generation.Processors;
using NSwag.Generation.Processors.Contexts;

public class NswagPostProcessor : IOperationProcessor
{
    public bool Process(OperationProcessorContext context)
    {
        var apiAction = ((AspNetCoreOperationProcessorContext)context).ApiDescription.ActionDescriptor;
        bool? isUnwantedController = apiAction?.DisplayName?.Contains("ExternalApiController");

        return !isUnwantedController.HasValue || isUnwantedController.Value == false;
    }
}

Then, in Program.cs, simply insert the custom processor into the processor pipeline to apply it:

builder.Services.AddOpenApiDocument(config =>
{
    config.OperationProcessors.Insert(0, new NswagPostProcessor());
});

The result of the Process operation determines whether the endpoint shows up in Swagger, so you can control it that way.

Tay answered 10/10, 2023 at 16:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.