如何在HotChocolate响应中显示枚举数值而非枚举名称
HotChocolate 返回枚举数值的解决方案
针对HotChocolate默认返回枚举名称、业务需要返回枚举数值的问题,有以下几种可行的实现方案:
1. 全局配置所有枚举返回数值
如果项目中所有枚举类型都需要以数值形式返回,可在GraphQL服务配置中全局设置:
builder.Services .AddGraphQLServer() .AddQueryType<Query>() // 其他必要配置(如添加类型、过滤器等) .ConfigureEnumTypes(enumType => { // 设置为false后,所有枚举默认返回对应数值 enumType.BindValuesToNames = false; });
这种方式一次性解决所有枚举的返回格式问题,无需逐个修改枚举或实体类。
2. 单独配置特定枚举类型
如果只需要修改某个特定枚举(比如CartStatus)的返回格式,可以自定义枚举类型配置:
首先创建枚举类型的配置类:
public class CartStatusEnumType : EnumType<CartStatus> { protected override void Configure(IEnumTypeDescriptor<CartStatus> descriptor) { // 让该枚举返回数值而非名称 descriptor.BindValuesToNames(false); // 若需要对单个枚举项做特殊映射,可单独配置(可选) // descriptor.Value(CartStatus.Building).Value(1); } }
然后在GraphQL服务配置中注册这个自定义枚举类型:
builder.Services .AddGraphQLServer() .AddQueryType<Query>() .AddEnumType<CartStatusEnumType>() // 其他配置
3. 字段级单独配置
如果仅需要修改Cart实体中Status字段的返回格式(其他枚举仍保留名称返回),可以通过以下两种方式实现:
方法A:使用属性标记
直接在实体类的字段上添加GraphQLType属性,指定返回类型为整数:
public class Cart : AuditableBaseEntity<Guid> { public Guid CourierId { get; set; } [GraphQLType(typeof(IntType))] public CartStatus Status { get; set; } = CartStatus.Building; public virtual ICollection<CartItem> Items { get; set; } = new HashSet<CartItem>(); }
方法B:自定义实体类型配置
创建Cart的类型配置类,指定Status字段的解析逻辑:
public class CartType : ObjectType<Cart> { protected override void Configure(IObjectTypeDescriptor<Cart> descriptor) { descriptor.Field(c => c.Status) .Type<IntType>() .Resolve(context => (int)context.Parent<Cart>().Status); } }
然后在服务配置中注册该类型:
builder.Services .AddGraphQLServer() .AddQueryType<Query>() .AddType<CartType>() // 其他配置
效果验证
配置完成后,查询返回的status字段将变为枚举对应的数值:
"data": { "actualCart": [ { "courierId": "efb60c9e-c6fe-4479-bd93-82fb23ad63b5", "status": 1 }, { "courierId": "efb60c9e-c6fe-4479-bd93-82fb23ad63b5", "status": 2 } ] }
内容的提问来源于stack exchange,提问作者Anton Moiseev
相关产品推荐
相关产品推荐

