CommonService.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. namespace Admin.NET.Core.Service;
  2. public class CommonService : ICommonService, IScoped
  3. {
  4. private readonly IHttpContextAccessor _httpContextAccessor;
  5. private readonly CodeGenOptions _codeGenOptions;
  6. public CommonService(IHttpContextAccessor httpContextAccessor,
  7. IOptions<CodeGenOptions> codeGenOptions)
  8. {
  9. _httpContextAccessor = httpContextAccessor;
  10. _codeGenOptions = codeGenOptions.Value;
  11. }
  12. /// <summary>
  13. /// 获取库表信息
  14. /// </summary>
  15. /// <returns></returns>
  16. public async Task<IEnumerable<EntityInfo>> GetEntityInfos()
  17. {
  18. var entityInfos = new List<EntityInfo>();
  19. var type = typeof(SugarTable);
  20. var type1 = typeof(NotTableAttribute);
  21. var types = new List<Type>();
  22. if (_codeGenOptions.EntityAssemblyNames != null)
  23. {
  24. foreach (var assemblyName in _codeGenOptions.EntityAssemblyNames)
  25. {
  26. Assembly asm = Assembly.Load(assemblyName);
  27. types.AddRange(asm.GetExportedTypes().ToList());
  28. }
  29. }
  30. Func<Attribute[], bool> IsMyAttribute = o =>
  31. {
  32. if (o.Where(c => c.GetType() == type1).Any()) return false;
  33. foreach (Attribute a in o)
  34. {
  35. if (a.GetType() == type && a.GetType() != type1)
  36. return true;
  37. }
  38. return false;
  39. };
  40. Type[] cosType = types.Where(o =>
  41. {
  42. return IsMyAttribute(Attribute.GetCustomAttributes(o, true));
  43. }
  44. ).ToArray();
  45. foreach (var c in cosType)
  46. {
  47. var sugarAttribute = c.GetCustomAttributes(type, true)?.FirstOrDefault();
  48. var des = c.GetCustomAttributes(typeof(DescriptionAttribute), true);
  49. var description = "";
  50. if (des.Length > 0)
  51. {
  52. description = ((DescriptionAttribute)des[0]).Description;
  53. }
  54. entityInfos.Add(new EntityInfo()
  55. {
  56. EntityName = c.Name,
  57. DbTableName = sugarAttribute == null ? c.Name : ((SugarTable)sugarAttribute).TableName,
  58. TableDescription = description
  59. });
  60. }
  61. return await Task.FromResult(entityInfos);
  62. }
  63. /// <summary>
  64. /// 获取Host
  65. /// </summary>
  66. /// <returns></returns>
  67. public string GetHost()
  68. {
  69. return $"{_httpContextAccessor.HttpContext.Request.Scheme}://{_httpContextAccessor.HttpContext.Request.Host.Value}";
  70. }
  71. /// <summary>
  72. /// 获取文件URL
  73. /// </summary>
  74. /// <param name="sysFile"></param>
  75. /// <returns></returns>
  76. public string GetFileUrl(SysFile sysFile)
  77. {
  78. return $"{GetHost()}/{sysFile.FilePath}/{sysFile.Id + sysFile.Suffix}";
  79. }
  80. }