GlobalActionMonitor.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. using Attribute;
  2. using Base;
  3. using Common;
  4. using Extensions;
  5. using Infrastructure;
  6. using Infrastructure.Model;
  7. using IPTools.Core;
  8. using Microsoft.AspNetCore.Mvc;
  9. using Microsoft.AspNetCore.Mvc.Controllers;
  10. using Microsoft.AspNetCore.Mvc.Diagnostics;
  11. using Microsoft.AspNetCore.Mvc.Filters;
  12. using NLog;
  13. using System.Text;
  14. using System.Web;
  15. namespace Middleware
  16. {
  17. public class GlobalActionMonitor : ActionFilterAttribute
  18. {
  19. static readonly Logger logger = LogManager.GetCurrentClassLogger();
  20. // private readonly ISysOperLogService OperLogService;
  21. public GlobalActionMonitor()
  22. {
  23. // OperLogService = operLogService;
  24. }
  25. /// <summary>
  26. /// Action请求前
  27. /// </summary>
  28. /// <param name="context"></param>
  29. /// <param name="next"></param>
  30. /// <returns></returns>
  31. public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
  32. {
  33. string content = "";
  34. if(context.HttpContext.Request.Method.ToLower() == "get")
  35. {
  36. content = context.HttpContext.GetQueryString();
  37. content = content.Substring(content.IndexOf("?") + 1);
  38. if(!string.IsNullOrEmpty(content))
  39. {
  40. string jsonString = "";
  41. string[] dataList = content.Split('&');
  42. foreach(string sub in dataList)
  43. {
  44. string[] item = sub.Split('=');
  45. jsonString += "\"" + item[0] + "\":\"" + item[1] + "\",";
  46. }
  47. content = "{" + jsonString.TrimEnd(',') + "}";
  48. }
  49. }
  50. else if(context.HttpContext.Request.Method.ToLower() == "delete")
  51. {
  52. string path = context.HttpContext.Request.Path.Value;
  53. content = path.Substring(path.LastIndexOf("/") + 1);
  54. }
  55. else
  56. {
  57. content = context.HttpContext.GetBody();
  58. }
  59. if(!string.IsNullOrEmpty(content))
  60. {
  61. if(content.Contains("{") && content.Contains("}") && content != "{}")
  62. {
  63. Dictionary<string, object> dictionary = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(content);
  64. if(context.ActionDescriptor.Parameters.Count > 0)
  65. {
  66. var parameters = context.ActionDescriptor.Parameters;
  67. foreach(var parameter in parameters)
  68. {
  69. string parameterName = parameter.Name;
  70. Type objectType = parameter.ParameterType;
  71. if(objectType.FullName != "System.String")
  72. {
  73. System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(objectType);
  74. var entry = assembly.CreateInstance(objectType.FullName);
  75. Type type = entry.GetType();
  76. System.Reflection.PropertyInfo[] propertyInfos = type.GetProperties();
  77. for (int i = 0; i < propertyInfos.Length; i++)
  78. {
  79. foreach (string key in dictionary.Keys)
  80. {
  81. if (propertyInfos[i].Name == key)
  82. {
  83. object value = dictionary[key];
  84. string ParameterType = propertyInfos[i].GetMethod.ReturnParameter.ParameterType.Name;
  85. if (ParameterType == "Int32")
  86. {
  87. if(value == null || value == "") value = "0";
  88. value = Convert.ToInt32(value);
  89. }
  90. else if (ParameterType == "Int64[]")
  91. {
  92. value = Tools.SpitLongArrary(Newtonsoft.Json.JsonConvert.SerializeObject(value).Replace("[", "").Replace("]", "").Trim('"'), ',');
  93. }
  94. else if (ParameterType == "Int32[]")
  95. {
  96. value = Tools.SpitIntArrary(Newtonsoft.Json.JsonConvert.SerializeObject(value).Replace("[", "").Replace("]", "").Trim('"'), ',');
  97. }
  98. else if (ParameterType == "List`1")
  99. {
  100. string val = Newtonsoft.Json.JsonConvert.SerializeObject(value).Replace("[", "").Replace("]", "").Trim('"');
  101. value = Tools.SpitLongArrary(val, ',').ToList();
  102. }
  103. if(value.ToString() == "-1") value = -1;
  104. if(value.ToString() == "[]") value = "";
  105. propertyInfos[i].SetValue(entry, value, null);
  106. break;
  107. }
  108. }
  109. }
  110. if(context.ActionArguments.ContainsKey(parameterName))
  111. {
  112. context.ActionArguments[parameterName] = entry;
  113. }
  114. else
  115. {
  116. context.ActionArguments.Add(parameterName, entry);
  117. }
  118. }
  119. }
  120. }
  121. }
  122. else
  123. {
  124. string ParamName = context.ActionDescriptor.Parameters[0].Name;
  125. if(context.ActionArguments.ContainsKey(ParamName))
  126. {
  127. context.ActionArguments[ParamName] = Convert.ToInt32(content);
  128. }
  129. else
  130. {
  131. context.ActionArguments.Add(ParamName, Convert.ToInt32(content));
  132. }
  133. }
  134. }
  135. else
  136. {
  137. if(context.ActionDescriptor.Parameters.Count > 0)
  138. {
  139. string ParamName = context.ActionArguments.Keys.First();
  140. object ParamValue = context.ActionArguments.Values.First();
  141. // ParamValue = DesDecrypt(ParamValue.ToString());
  142. if(ParamValue.GetType() == typeof(int))
  143. {
  144. ParamValue = (int)ParamValue;
  145. }
  146. if(context.ActionArguments.ContainsKey(ParamName))
  147. {
  148. context.ActionArguments[ParamName] = ParamValue;
  149. }
  150. else
  151. {
  152. context.ActionArguments.Add(ParamName, ParamValue);
  153. }
  154. }
  155. }
  156. string msg = string.Empty;
  157. var values = context.ModelState.Values;
  158. foreach (var item in values)
  159. {
  160. foreach (var err in item.Errors)
  161. {
  162. if (!string.IsNullOrEmpty(msg))
  163. {
  164. msg += " | ";
  165. }
  166. msg += err.ErrorMessage;
  167. }
  168. }
  169. if (!string.IsNullOrEmpty(msg))
  170. {
  171. ApiResult response = new((int)ResultCode.PARAM_ERROR, msg);
  172. context.Result = new JsonResult(response);
  173. }
  174. return base.OnActionExecutionAsync(context, next);
  175. }
  176. /// <summary>
  177. /// OnActionExecuted是在Action中的代码执行之后运行的方法。
  178. /// </summary>
  179. /// <param name="context"></param>
  180. public override void OnResultExecuted(ResultExecutedContext context)
  181. {
  182. if (context.ActionDescriptor is not ControllerActionDescriptor controllerActionDescriptor) return;
  183. //获得注解信息
  184. LogAttribute logAttribute = GetLogAttribute(controllerActionDescriptor);
  185. if (logAttribute == null) return;
  186. try
  187. {
  188. string method = context.HttpContext.Request.Method.ToUpper();
  189. // 获取当前的用户
  190. string userName = context.HttpContext.GetName() ?? context.HttpContext.Request.Headers["userName"];
  191. string jsonResult = string.Empty;
  192. if (context.Result is ContentResult result && result.ContentType == "application/json")
  193. {
  194. jsonResult = result.Content.Replace("\r\n", "").Trim();
  195. }
  196. if (context.Result is JsonResult result2)
  197. {
  198. jsonResult = result2.Value?.ToString();
  199. }
  200. //获取当前执行方法的类名
  201. //string className = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
  202. //获取当前成员的名称
  203. //string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
  204. string controller = context.RouteData.Values["Controller"].ToString();
  205. string action = context.RouteData.Values["Action"].ToString();
  206. string ip = HttpContextExtension.GetClientUserIp(context.HttpContext);
  207. var ip_info = IpTool.Search(ip);
  208. // SysOperLog sysOperLog = new()
  209. // {
  210. // Status = 0,
  211. // OperName = userName,
  212. // OperIp = ip,
  213. // OperUrl = HttpContextExtension.GetRequestUrl(context.HttpContext),
  214. // RequestMethod = method,
  215. // JsonResult = jsonResult,
  216. // OperLocation = HttpContextExtension.GetIpInfo(ip),
  217. // Method = controller + "." + action + "()",
  218. // //Elapsed = _stopwatch.ElapsedMilliseconds,
  219. // OperTime = DateTime.Now,
  220. // OperParam = HttpContextExtension.GetRequestValue(context.HttpContext, method)
  221. // };
  222. if (logAttribute != null)
  223. {
  224. // sysOperLog.Title = logAttribute?.Title;
  225. // sysOperLog.BusinessType = (int)logAttribute.BusinessType;
  226. // sysOperLog.OperParam = logAttribute.IsSaveRequestData ? sysOperLog.OperParam : "";
  227. // sysOperLog.JsonResult = logAttribute.IsSaveResponseData ? sysOperLog.JsonResult : "";
  228. }
  229. LogEventInfo ei = new(NLog.LogLevel.Info, "GlobalActionMonitor", "");
  230. ei.Properties["jsonResult"] = !HttpMethods.IsGet(method) ? jsonResult : "";
  231. // ei.Properties["requestParam"] = sysOperLog.OperParam;
  232. ei.Properties["user"] = userName;
  233. logger.Log(ei);
  234. // OperLogService.InsertOperlog(sysOperLog);
  235. }
  236. catch (Exception ex)
  237. {
  238. logger.Error(ex, $"记录操作日志出错了#{ex.Message}");
  239. }
  240. }
  241. private LogAttribute GetLogAttribute(ControllerActionDescriptor controllerActionDescriptor)
  242. {
  243. var attribute = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
  244. .FirstOrDefault(a => a.GetType().Equals(typeof(LogAttribute)));
  245. return attribute as LogAttribute;
  246. }
  247. private string DesDecrypt(string content)
  248. {
  249. content = HttpUtility.UrlDecode(content);
  250. return Dbconn.DesDecrypt(content, AppSettings.GetConfig("ApiKey"));
  251. }
  252. }
  253. }