Search code examples
.netasp.net-mvcasp.net-coreswaggeropenapi

How to remove quote sign and number from generic type names in Swagger for ASP.NET Core?


I am developing an API using ASP.NET Core and ("openapi": "3.0.1") for generating documentation. However, when using generic types, Swagger generates schema names with quote and numbers, like: ApiResponse`1[AlarmItem[]].

Here’s a simplified version of my generic type:

public class ApiResponse<T>
{
    public T Data { get; set; }
}

public class AlarmItem
{
    public string Name { get; set; }
}

I would like Swagger to display the schema names more clearly, without the tilde and numbers, something like ApiResponse[AlarmItem[]]. For me it's required to keep the same style which was with previous versions ("swagger": "2.0")


Solution

  • I you are using Swashbuckle you can customize it by providing a CustomSchemaIds:

    services.AddSwaggerGen(options =>
    {
      // ...
      options.CustomSchemaIds(type => "your convention here");
    }
    

    You can for example inspect the flag type.IsGenericType and decide what to return.