GlobalActionMonitor.cs 13 KB

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