RicoSuter / NSwag

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
http://NSwag.org
MIT License
6.77k stars 1.29k forks source link

Specify controller types using AspNetCore middleware #2765

Open KontoBruktUnderUtdanning opened 4 years ago

KontoBruktUnderUtdanning commented 4 years ago

I use NSwag to generate Swagger UIs for my endpoints in a .NET Framework project. I do it like this, using the NSwag.AspNet.Owin package:

RouteTable.Routes.MapOwinPath("swagger", app =>
   {
      app.UseSwaggerUi3(controllerTypes, settings =>
      {
         ...
      });
   });

Notice how I can specify which controllers are displayed in the UI.

Now I'm working on a .NET Core project and would like to do the same. Using the AspNetCore middleware package seems like the most modern approach.

services.AddOpenApiDocument((settings, provider) =>
   {
      ...
   });

...

app.UseOpenApi(settings =>
   {
      ...
   });

app.UseSwaggerUi3(settings =>
   {
      ...
   });

This is from the NSwag.AspNetCore package. It gives me a UI, but it includes endpoints from all of my controllers. I want to specify which controller types are to be used when generating the document/UI. This is easy using the Owin package, but I cannot find any such setting in the AspNetCore middleware. What am I missing?

RicoSuter commented 4 years ago

In AddOpenApiDocument you can add a custom operation processor and return false for the operations/controllers you want to exclude

RicoSuter commented 4 years ago

Insert the processor at index 0 so that it is executed first

RicoSuter commented 4 years ago

See https://github.com/RicoSuter/NSwag/wiki/Document-Processors-and-Operation-Processors#operation-processors

jeremyVignelles commented 4 years ago

The canonical way to do that with the new asp.net core is to put your controllers into groups :

    [ApiController]
    [ApiExplorerSettings(GroupName = "MyGroup")]
    public class MyController: Controller

In the NSwag document generation method, just put:

            settings.Title = "My API";
            settings.Description = "My SUPER API";
            settings.Version = "v1";
            settings.ApiGroupNames = new[] {"MyGroup"};

Only the controllers from MyGroup will get generated.