MvcActionHelper.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System.Collections.Generic;
  2. using System.Reflection;
  3. namespace CommonTool
  4. {
  5. public class MvcActionHelper
  6. {
  7. // ReSharper disable once StaticMemberInitializerReferesToMemberBelow
  8. public static MvcActionHelper Instance { get; } = new MvcActionHelper(AssemblyName);
  9. public MvcActionHelper(string assemblyName)
  10. {
  11. AssemblyName = assemblyName;
  12. ActionPermissions = GetAllActionByAssembly(assemblyName);
  13. }
  14. public static string AssemblyName { get; set; }
  15. public IList<ActionPermission> ActionPermissions { get; set; }
  16. public IList<ActionPermission> GetAllActionByAssembly(string assemblyName)
  17. {
  18. var result = new List<ActionPermission>();
  19. var types = Assembly.Load(assemblyName).GetTypes();
  20. foreach (var type in types)
  21. {
  22. if (type.BaseType != null && type.BaseType.Name == "BaseController")//如果是Controller
  23. {
  24. var members = type.GetMethods();
  25. foreach (var member in members)
  26. {
  27. if (member.ReturnType.Name == "ActionResult")//如果是Action
  28. {
  29. if (member.DeclaringType != null)
  30. {
  31. ActionPermission ap = new ActionPermission
  32. {
  33. ActionName = member.Name,
  34. ControllerName = member.DeclaringType.Name.Substring(0, member.DeclaringType.Name.Length - 10)
  35. };
  36. // 去掉“Controller”后缀
  37. object[] attrs = member.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true);
  38. if (attrs.Length > 0)
  39. {
  40. var descriptionAttribute = attrs[0] as System.ComponentModel.DescriptionAttribute;
  41. if (descriptionAttribute != null)
  42. ap.Description = descriptionAttribute.Description;
  43. }
  44. result.Add(ap);
  45. }
  46. }
  47. }
  48. }
  49. }
  50. return result;
  51. }
  52. /// <summary>
  53. /// 针对MVC的Action的权限
  54. /// </summary>
  55. public class ActionPermission
  56. {
  57. /// <summary>
  58. /// 请求地址
  59. /// </summary>
  60. public virtual string ActionName { get; set; }
  61. /// <summary>
  62. /// 请求地址
  63. /// </summary>
  64. public virtual string ControllerName { get; set; }
  65. /// <summary>
  66. /// 描述
  67. /// </summary>
  68. public virtual string Description { get; set; }
  69. ///// <summary>
  70. ///// 角色列表
  71. ///// </summary>
  72. //public virtual ISet<Role> Roles { get; set; }
  73. }
  74. }
  75. }