RicoSuter / NSwag

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

Choose controllers to generate typescript clients from #4907

Closed JanBN closed 3 weeks ago

JanBN commented 1 month ago

Hello,

prior to version 14 I did use the reflection option and chose only a few controllers to generate the typescript client from.

I'm trying to update to version 14 and cannot find an option to include only a few controllers, not all from my project.

How can I do this ?

JanBN commented 3 weeks ago

So this is how I made it to work:

I found out there is an attribute [ApiExplorerSettings(IgnoreApi = true)] which you can put on controller. Now I want to put this attribute to all controllers. - https://stackoverflow.com/questions/77202870/add-attribute-to-all-controllers

This is the code I have in my startup ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
  ...
  var entryAssembly = Assembly.GetEntryAssembly();
  var isNswagRunning = entryAssembly?.FullName?.StartsWith("NSwag") ?? false;
  var controllesWithView = services.AddControllersWithViews(options =>
  {
      if (isNswagRunning)
      {
          options.Conventions.Add(new IgnoreApiConvention());
      }
  })
  .AddRazorRuntimeCompilation();
  ...
}
...

public class IgnoreApiConvention : IControllerModelConvention
{
    public void Apply(ControllerModel controller)
    {
        var apiExplorerSettingAttribute = controller.Attributes.FirstOrDefault(x => x is ApiExplorerSettingsAttribute) as ApiExplorerSettingsAttribute;
        var hasAttributeEnablingGeneration = apiExplorerSettingAttribute != null && apiExplorerSettingAttribute.IgnoreApi == false;

        if (hasAttributeEnablingGeneration == false)
        {
            // Add the [ApiExplorerSettings(IgnoreApi = true)] attribute to all controllers            
            controller.ApiExplorer.IsVisible = false;
        }
    }
}

And now all controllers are ignored by default. When I want to include controller into nswag generation I need to add this attribute to the controller

[ApiExplorerSettings(IgnoreApi = false)]