ApiConvention.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. using Infrastructure.Helper;
  2. using Microsoft.AspNetCore.Mvc.ActionConstraints;
  3. using Microsoft.AspNetCore.Mvc.ApplicationModels;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. namespace ZR.Common.DynamicApiSimple;
  9. class ApiConvention : IApplicationModelConvention
  10. {
  11. public void Apply(ApplicationModel application)
  12. {
  13. foreach (var controller in application.Controllers)
  14. {
  15. var type = controller.ControllerType;
  16. if (typeof(IDynamicApi).IsAssignableFrom(type) || type.IsDefined(typeof(DynamicApiAttribute), true))
  17. {
  18. ClearAction(controller);
  19. ConfigureApiExplorer(controller);
  20. ConfigureSelector(controller);
  21. }
  22. }
  23. }
  24. private void ClearAction(ControllerModel controller)
  25. {
  26. Type genericBaseType = AssemblyUtils.GetGenericTypeByName("BaseService`1");
  27. var needRemoveAction = controller.Actions
  28. .Where(action => !action.ActionMethod.DeclaringType.IsDerivedFromGenericBaseRepository(genericBaseType))
  29. .ToList();
  30. foreach (var actionModel in needRemoveAction)
  31. {
  32. controller.Actions.Remove(actionModel);
  33. }
  34. }
  35. private static void ConfigureApiExplorer(ControllerModel controller)
  36. {
  37. if (!controller.ApiExplorer.IsVisible.HasValue)
  38. controller.ApiExplorer.IsVisible = true;
  39. foreach (var action in controller.Actions)
  40. {
  41. if (!action.ApiExplorer.IsVisible.HasValue)
  42. {
  43. action.ApiExplorer.IsVisible = true;
  44. }
  45. }
  46. }
  47. private void ConfigureSelector(ControllerModel controller)
  48. {
  49. RemoveEmptySelectors(controller.Selectors);
  50. if (controller.Selectors.Any(selector => selector.AttributeRouteModel != null))
  51. return;
  52. foreach (var action in controller.Actions)
  53. {
  54. ConfigureSelector(action);
  55. }
  56. }
  57. private static void RemoveEmptySelectors(IList<SelectorModel> selectors)
  58. {
  59. for (var i = selectors.Count - 1; i >= 0; i--)
  60. {
  61. var selector = selectors[i];
  62. if (selector.AttributeRouteModel == null &&
  63. (selector.ActionConstraints == null || selector.ActionConstraints.Count <= 0) &&
  64. (selector.EndpointMetadata == null || selector.EndpointMetadata.Count <= 0))
  65. {
  66. selectors.Remove(selector);
  67. }
  68. }
  69. }
  70. private void ConfigureSelector(ActionModel action)
  71. {
  72. RemoveEmptySelectors(action.Selectors);
  73. if (action.Selectors.Count <= 0)
  74. AddServiceSelector(action);
  75. else
  76. NormalizeSelectorRoutes(action);
  77. }
  78. private void AddServiceSelector(ActionModel action)
  79. {
  80. var template = new Microsoft.AspNetCore.Mvc.RouteAttribute(GetRouteTemplate(action));
  81. var selector = new SelectorModel
  82. {
  83. AttributeRouteModel = new AttributeRouteModel(template)
  84. };
  85. selector.ActionConstraints.Add(new HttpMethodActionConstraint(new[] { GetHttpMethod(action) }));
  86. action.Selectors.Add(selector);
  87. }
  88. private void NormalizeSelectorRoutes(ActionModel action)
  89. {
  90. foreach (var selector in action.Selectors)
  91. {
  92. var template = new Microsoft.AspNetCore.Mvc.RouteAttribute(GetRouteTemplate(action,selector));
  93. selector.AttributeRouteModel = new AttributeRouteModel(template);
  94. if (selector.ActionConstraints.OfType<HttpMethodActionConstraint>().FirstOrDefault()?.HttpMethods?.FirstOrDefault() == null)
  95. selector.ActionConstraints.Add(new HttpMethodActionConstraint(new[] { GetHttpMethod(action) }));
  96. }
  97. }
  98. private string GetRouteTemplate(ActionModel action,SelectorModel selectorModel=null)
  99. {
  100. var routeTemplate = new StringBuilder();
  101. var names = action.Controller.ControllerType.Namespace.Split('.');
  102. if (names.Length > 2)
  103. {
  104. routeTemplate.Append(names[^2]);
  105. }
  106. // Controller
  107. var controllerName = action.Controller.ControllerName;
  108. if (controllerName.EndsWith("Service"))
  109. controllerName = controllerName[0..^7];
  110. if (selectorModel is { AttributeRouteModel: not null })
  111. {
  112. if (!string.IsNullOrWhiteSpace(selectorModel.AttributeRouteModel?.Template))
  113. {
  114. if (selectorModel.AttributeRouteModel.Template.StartsWith("/"))
  115. {
  116. routeTemplate.Append(selectorModel.AttributeRouteModel.Template);
  117. }
  118. else
  119. {
  120. routeTemplate.Append($"{BaseRoute}/{controllerName}/{selectorModel.AttributeRouteModel.Template}");
  121. }
  122. }
  123. }
  124. else
  125. {
  126. routeTemplate.Append($"{BaseRoute}/{controllerName}");
  127. // Action
  128. var actionName = action.ActionName;
  129. if (actionName.EndsWith("Async") || actionName.EndsWith("async"))
  130. actionName = actionName[..^"Async".Length];
  131. if (!string.IsNullOrEmpty(actionName))
  132. {
  133. routeTemplate.Append($"/{RemoveHttpMethodPrefix(actionName)}");
  134. }
  135. }
  136. return routeTemplate.ToString();
  137. }
  138. private static string GetHttpMethod(ActionModel action)
  139. {
  140. var actionName = action.ActionName.ToLower();
  141. string Method = string.Empty;
  142. if (!string.IsNullOrEmpty(actionName))
  143. {
  144. Method = GetName(actionName);
  145. }
  146. return Method;
  147. }
  148. private static string GetName(string actionName)
  149. {
  150. string result = "GET";
  151. foreach (string key in Methods.Keys)
  152. {
  153. if (actionName.Contains(key))
  154. {
  155. result = Methods[key];
  156. break;
  157. }
  158. }
  159. return result;
  160. }
  161. internal static Dictionary<string, string> Methods { get; private set; }
  162. internal static string BaseRoute { get; private set; } = "api";
  163. static ApiConvention()
  164. {
  165. Methods = new Dictionary<string, string>()
  166. {
  167. ["get"] = "GET",
  168. ["find"] = "GET",
  169. ["fetch"] = "GET",
  170. ["query"] = "GET",
  171. ["post"] = "POST",
  172. ["add"] = "POST",
  173. ["create"] = "POST",
  174. ["insert"] = "POST",
  175. ["submit"] = "POST",
  176. ["put"] = "POST",
  177. ["update"] = "POST",
  178. ["delete"] = "DELETE",
  179. ["remove"] = "DELETE",
  180. ["clear"] = "DELETE",
  181. ["patch"] = "PATCH"
  182. };
  183. }
  184. private static string RemoveHttpMethodPrefix(string actionName)
  185. {
  186. foreach (var method in Methods.Keys)
  187. {
  188. if (actionName.StartsWith(method, StringComparison.OrdinalIgnoreCase))
  189. {
  190. // 移除前缀并返回结果
  191. return actionName.Substring(method.Length);
  192. }
  193. }
  194. return actionName; // 如果没有找到前缀,返回原始名称
  195. }
  196. }