如何通过TypeSpec生成含正确名称与注释的规范C#枚举?
我们用TypeSpec定义Web API时需要添加一个大型枚举,初始TypeSpec代码如下:
/** * Enumeration of all possible device types. */ enum DeviceType { /** * Unknown DeviceType * UNKNOWN_DEVICETYPE * */ UnknownDeviceType: -1, /** * Some other device type * OTHER_DEVICETYPE */ OtherDeviceType: 0, /** * Some fancy device type * FANCY_DEVICE */ SomeFancyDeviceType: 1, ... }
通过tsp compile和java -jar openapi-generator-cli-7.8.0.jar generate转换后,得到的OpenAPI内容缺失了枚举成员的名称和注释:
DeviceType: type: number enum: - -1 - 0 - 1
进一步生成的C#枚举也没有保留原有名称和注释,只生成了无意义的自动命名成员:
/// <summary> /// Enumeration of all possible device types based on table `dbo.DeviceTypes`. /// </summary> /// <value>Enumeration of all possible device types based on table `dbo.DeviceTypes`.</value> public enum DeviceType { /// <summary> /// Enum _1Enum for -1 /// </summary> [EnumMember(Value = "-1")] _1Enum = 1, /// <summary> /// Enum _0Enum for 0 /// </summary> [EnumMember(Value = "0")] _0Enum = 2, /// <summary> /// Enum _1Enum2 for 1 /// </summary> [EnumMember(Value = "1")] _1Enum2 = 3, ... }
如何通过TypeSpec生成包含规范枚举名称和注释的定义?
要让TypeSpec生成带成员名称、注释的OpenAPI枚举,进而让OpenAPI Generator生成规范的C#枚举,需按以下步骤配置:
1. 启用TypeSpec OpenAPI扩展的枚举保留功能
TypeSpec默认生成的OpenAPI枚举仅包含值,需通过配置开启成员名称和描述的保留。可以修改项目根目录的tspconfig.yaml:
emitters: "@typespec/openapi": options: include-enum-descriptions: true include-enum-names: true
也可以直接在TypeSpec代码中通过@use指令配置:
@use("@typespec/openapi", { includeEnumDescriptions: true, includeEnumNames: true })
2. 规范TypeSpec枚举的注释格式
确保枚举成员的注释符合TypeSpec规范,注释内容会被提取为OpenAPI枚举的description字段。优化后的枚举示例:
/** * Enumeration of all possible device types. */ enum DeviceType { /** * Unknown device type */ UnknownDeviceType: -1, /** * Other device type */ OtherDeviceType: 0, /** * Fancy device type */ SomeFancyDeviceType: 1, }
3. 重新编译并生成代码
重新执行tsp compile,此时生成的OpenAPI会包含枚举成员的名称和描述扩展字段:
DeviceType: type: number enum: - -1 - 0 - 1 x-enum-varnames: - UnknownDeviceType - OtherDeviceType - SomeFancyDeviceType x-enum-descriptions: - Unknown device type - Other device type - Fancy device type
再用OpenAPI Generator生成C#代码时,会自动识别这些扩展字段,生成符合预期的枚举:
/// <summary> /// Enumeration of all possible device types. /// </summary> public enum DeviceType { /// <summary> /// Unknown device type /// </summary> [EnumMember(Value = "-1")] UnknownDeviceType = -1, /// <summary> /// Other device type /// </summary> [EnumMember(Value = "0")] OtherDeviceType = 0, /// <summary> /// Fancy device type /// </summary> [EnumMember(Value = "1")] SomeFancyDeviceType = 1, }
4. OpenAPI Generator额外参数配置(可选)
如果生成的C#枚举仍有异常,可以在生成命令中添加参数强化配置:
java -jar openapi-generator-cli-7.8.0.jar generate \ -i openapi.json \ -g csharp \ --additional-properties=enumPropertyNaming=original,useEnumExtension=true
enumPropertyNaming=original确保枚举成员名称保留原始定义,useEnumExtension=true启用对x-enum-varnames等扩展字段的支持。
内容的提问来源于stack exchange,提问作者André Reichelt

