SysEnumDataService.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. namespace Admin.NET.Core.Service;
  2. /// <summary>
  3. /// 枚举服务
  4. /// </summary>
  5. [ApiDescriptionSettings(Order = 1000)]
  6. [AllowAnonymous]
  7. public class SysEnumDataService : IDynamicApiController, ITransient
  8. {
  9. private readonly EnumOptions _enumOptions;
  10. public SysEnumDataService(IOptions<EnumOptions> enumOptions)
  11. {
  12. _enumOptions = enumOptions.Value;
  13. }
  14. /// <summary>
  15. /// 获取所有枚举类型
  16. /// </summary>
  17. /// <returns></returns>
  18. [HttpGet]
  19. public List<EnumTypeOutput> GetEnumTypeList()
  20. {
  21. List<EnumTypeOutput> result = new List<EnumTypeOutput>();
  22. var enumTypeList = App.EffectiveTypes.Where(t => t.IsEnum && _enumOptions.EntityAssemblyNames.Contains(t.Assembly.GetName().Name)).ToList();
  23. foreach (var item in enumTypeList)
  24. {
  25. result.Add(GetEnumDescription(item));
  26. }
  27. return result;
  28. }
  29. private EnumTypeOutput GetEnumDescription(Type type)
  30. {
  31. string description = type.Name;
  32. var attrs = type.GetCustomAttributes(typeof(DescriptionAttribute), false);
  33. if (attrs.Any())
  34. {
  35. //获取到:超级管理员
  36. var att = ((DescriptionAttribute[])attrs)[0];
  37. description = att.Description;
  38. }
  39. return new EnumTypeOutput
  40. {
  41. TypeDescribe = description,
  42. TypeName = type.Name,
  43. TypeRemark = description
  44. };
  45. }
  46. /// <summary>
  47. /// 通过枚举类型获取枚举值集合
  48. /// </summary>
  49. /// <param name="input"></param>
  50. /// <returns></returns>
  51. [HttpGet]
  52. public List<EnumEntity> GetEnumDataList([FromQuery] EnumDataInput input)
  53. {
  54. // 查找枚举
  55. var enumType = App.EffectiveTypes.FirstOrDefault(t => t.IsEnum && t.Name == input.EnumName);
  56. if (enumType is not { IsEnum: true })
  57. throw Oops.Oh(ErrorCodeEnum.D1503);
  58. return enumType.EnumToList();
  59. }
  60. /// <summary>
  61. /// 通过实体的字段名获取相关枚举值集合(目前仅支持枚举类型)
  62. /// </summary>
  63. /// <param name="input"></param>
  64. /// <returns></returns>
  65. [HttpGet]
  66. public List<EnumEntity> GetEnumDataListByField([FromQuery] QueryEnumDataInput input)
  67. {
  68. // 获取实体类型属性
  69. Type entityType = App.EffectiveTypes.FirstOrDefault(t =>t.Name == input.EntityName) ?? throw Oops.Oh(ErrorCodeEnum.D1504);
  70. // 获取字段类型
  71. var fieldType = entityType.GetProperties().FirstOrDefault(p => p.Name == input.FieldName)?.PropertyType;
  72. if (fieldType is not { IsEnum: true })
  73. throw Oops.Oh(ErrorCodeEnum.D1503);
  74. return fieldType.EnumToList();
  75. }
  76. }