You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.Net Core如何通过HTTP GET接口返回枚举值及对应Description属性列表

问题修正与实现方案

现有代码存在的问题

  • 接口设置了单个枚举类型入参,只能查询单个枚举值的描述,无法返回全量枚举列表
  • 返回值类型声明List<IActionResult>错误,和实际返回的内容格式不匹配
  • 缺少遍历枚举所有成员、批量获取属性的逻辑

完整实现代码

1. 补充获取枚举描述属性的通用扩展方法(如果你还没有实现对应方法的话)

using System.ComponentModel;
using System.Reflection;

public static class EnumExtensions
{
    public static string GetDescription(this Enum enumValue)
    {
        FieldInfo field = enumValue.GetType().GetField(enumValue.ToString());
        DescriptionAttribute attribute = field.GetCustomAttribute<DescriptionAttribute>();
        // 没有标注Description属性时默认返回枚举名
        return attribute == null ? enumValue.ToString() : attribute.Description;
    }
}

2. 修正后的GET接口代码

// 自定义返回结构,可根据你的业务需求调整字段
public class EnumOptionDto
{
    public int Value { get; set; }
    public string EnumName { get; set; }
    public string Description { get; set; }
}

[HttpGet("GetAllNotificationTemplateTypes")]
public IActionResult GetAllNotificationTemplateTypes()
{
    var result = Enum.GetValues<NotificationTemplateType>()
        .Select(e => new EnumOptionDto
        {
            Value = (int)e,
            EnumName = e.ToString(),
            Description = e.GetDescription()
        })
        .ToList();
    return Ok(result);
}

调用效果

调用该GET接口后会返回如下格式的全量枚举列表:

[
  {
    "value": 0,
    "enumName": "NotTemplate",
    "description": "Şablonsuz"
  },
  {
    "value": 100,
    "enumName": "NewUser",
    "description": "Yeni Kullanıcı Şablonu"
  },
  {
    "value": 101,
    "enumName": "ForgotPassword",
    "description": "Şifremi Unuttum Şablonu"
  },
  {
    "value": 200,
    "enumName": "NewSeller",
    "description": "Yeni Satıcı Şablonu"
  }
]

如果只需要返回描述内容,调整Select逻辑直接返回e.GetDescription()即可。

内容的提问来源于stack exchange,提问作者user16695025

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 00:48:05