Swagger能否生成与C#输入模型一致的泛型输出模型?
ApiResult<T> via Swagger Codegen Absolutely! You can get Swagger Codegen to generate a generic TypeScript interface that matches your C# ApiResult<T> structure. The issue you're seeing happens because Swagger (by default) expands generic type instances into concrete, non-generic names like ApiResultString, and older Codegen configurations don't preserve generic definitions. Here's how to fix it step by step:
Step 1: Configure Swagger to Preserve Generic Type Definitions
First, make sure your C# Swagger setup (using Swashbuckle) outputs the generic type structure instead of expanding it into concrete names.
In your .NET project's startup configuration (either Startup.cs for .NET 5 and below, or Program.cs for .NET 6+):
services.AddSwaggerGen(c => { // Include XML comments to help Swagger understand your types (optional but recommended) var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); // Customize schema IDs to retain generic type syntax (e.g., ApiResult<T> instead of ApiResultString) c.CustomSchemaIds(type => { if (type.IsGenericType) { // Extract the base generic name (strip the `1` suffix) and list generic arguments var genericBaseName = type.Name.Split('`')[0]; var genericArgs = string.Join(",", type.GetGenericArguments().Select(t => t.Name)); return $"{genericBaseName}<{genericArgs}>"; } return type.Name; }); });
After this change, your Swagger schema will show ApiResult<string> instead of ApiResultString—this is key for Codegen to recognize the generic structure.
Step 2: Configure Swagger Codegen to Generate Generic Interfaces
Next, tell Swagger Codegen to generate generic TypeScript types instead of concrete ones. Use the supportsGenericInterfaces=true additional property when running Codegen.
Example Command Line Usage:
swagger-codegen generate -i path/to/your/swagger.json -l typescript-angular -o ./generated-types --additional-properties=supportsGenericInterfaces=true
Example Maven Plugin Configuration:
If you're using the Maven plugin, add the property to your pom.xml:
<build> <plugins> <plugin> <groupId>io.swagger.codegen.v3</groupId> <artifactId>swagger-codegen-maven-plugin</artifactId> <version>3.0.34</version> <executions> <execution> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>path/to/your/swagger.json</inputSpec> <language>typescript-angular</language> <output>./generated-types</output> <additionalProperties>supportsGenericInterfaces=true</additionalProperties> </configuration> </execution> </executions> </plugin> </plugins> </build>
Step 3: Verify the Generated TypeScript Code
Once you run Codegen with these settings, you'll get a generic interface that matches your original C# model:
'use strict'; export interface ApiResult<T> { result?: T; success?: boolean; }
You can now use this exactly like your C# generic type—e.g., ApiResult<string>, ApiResult<YourCustomModel>, etc.
Key Notes:
- Use Updated Versions: Ensure you're using a recent version of
Swashbuckle.AspNetCore(v5+ recommended) and Swagger Codegen (v3+), as older versions have limited generic support. - Template Compatibility: The
supportsGenericInterfacesproperty works with most TypeScript templates (liketypescript-angular,typescript-node,typescript-fetch). Double-check your template's documentation if you run into issues. - Manual Swagger JSON Fix (If Needed): If you can't adjust the .NET Swagger setup, you can manually edit your
swagger.jsonto replace concrete generic instances with a generic schema definition before running Codegen.
内容的提问来源于stack exchange,提问作者MelnikovI

