RicoSuter / NSwag

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

Exclude models from schema generation #3178

Open sascha-andres opened 3 years ago

sascha-andres commented 3 years ago

I want to exclude Models from the schema. I tried to do that with SchemaProcessor:

internal class SwaggerSchemaProcessor : ISchemaProcessor
{
  public void Process( SchemaProcessorContext context )
  {
    context.Settings.ExcludedTypeNames = new[] { "PM.Api.Data.BusinessUnit" };
  }
}

I registered it like this:

services.AddSwaggerDocument( document => {
                                 document.SchemaProcessors.Add( new SwaggerSchemaProcessor () );
                               } );

Unfortunately this does not work. And for some Models I do not own the code, so for those I can not use attributes.

Any help appreciated.

RicoSuter commented 3 years ago

Within an ISchemaProcessor you must not mutate settings... This setting needs to be set before the generation is run, ie with document => document.ExcludedTypeNames...

RicoSuter commented 3 years ago

You cannot really exclude types with this, it is only applicable with base types so that inheritance chains are not generated. This is the only place: https://github.com/RicoSuter/NJsonSchema/blob/master/src/NJsonSchema/Generation/JsonSchemaGenerator.cs#L1022

Just ignoring a type cannot work as they are needed in the public API... but you can map your type to eg "object" with a a new mapper in TypeMappers.

There is another setting for the code generators ExcludedTypeNames where you can exclude schemas from being generated at all (produces not compilable code) but this is not the thing you're looking for i suppose.

GFoley83 commented 10 months ago

~@RicoSuter Is it possible to just hide the "Schemas" section from the UI entirely? If so, how? Thanks.~ Never mind. Found it here: https://github.com/RicoSuter/NSwag/blob/512eb654b1be5714c7923b74d22e2049d56b5622/src/NSwag.AspNetCore/SwaggerUiSettings.cs#L89C31-L89C31

app.UseSwaggerUi3(ui =>
{
    ui.DefaultModelsExpandDepth = -1;
})