NSwag namespace in model names

When using NSwag via C#, you can provide an own TypeNameGenerator (via the settings object) to customize the way how the class names are generated.


I've found a solution using a custom SchemaNameGenerator instead of a custom TypeNameGenerator (where I don't have package information).

internal class MySchemaNameGenerator : DefaultSchemaNameGenerator, ISchemaNameGenerator
{
    public override string Generate(Type type)
    {
        string retValue = base.Generate(type);
        // Quite ugly but do fix the concept
        if (retValue.Equals("BaseClass"))
        {
            retValue = type.FullName.Replace(".","_");
        }
        return retValue;
    }
}

Always set through settings:

 app.UseSwaggerUi(typeof(WebApiApplication).Assembly, new SwaggerUiSettings
                {
                    SchemaNameGenerator = new MySchemaNameGenerator(),
                    ...

This way I get something more meaningful

"/api/test/models/base": {
      "get": {
        "tags": [
          "Test"
        ],
        "operationId": "Test_Get2",
        "parameters": [],
        "responses": {
          "200": {
            "description": "",
            "schema": {
              "$ref": "#/definitions/WebApi_Models_BaseClass"
            },
            "x-nullable": true
          }
        }
      }
    },
    "/api/test/models/extended": {
      "get": {
        "tags": [
          "Test"
        ],
        "operationId": "Test_Get3",
        "parameters": [],
        "responses": {
          "200": {
            "description": "",
            "schema": {
              "$ref": "#/definitions/ExtendedClass"
            },
            "x-nullable": true
          }
        }
      }
    },
    "/api/test/modelli/base": {
      "get": {
        "tags": [
          "Test"
        ],
        "operationId": "Test_Get4",
        "parameters": [],
        "responses": {
          "200": {
            "description": "",
            "schema": {
              "$ref": "#/definitions/WebApi_Modelli_BaseClass"
            },
            "x-nullable": true
          }
        }
      }
    },

Even if the discriminator property for polymorphism wants the base name "BaseClass".


Let me update shadowsheep's answer for a more recent version of NSwag:

services.AddSwaggerDocument(cfg => { cfg.SchemaNameGenerator = new CustomSchemaNameGenerator(); });

With:

internal class CustomSchemaNameGenerator : ISchemaNameGenerator
{
    public string Generate(Type type)
    {
        return type.FullName.Replace(".", "_");
    }
}

Tags:

Nswag