GlobalActionMonitor.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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("v1/"))
  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 == "Decimal")
  98. {
  99. if(value == null || value == "") value = "0";
  100. value = Convert.ToDecimal(value);
  101. }
  102. else if(ParameterType == "Boolean")
  103. {
  104. if(value == null || value == "") value = false;
  105. }
  106. else if (ParameterType == "Int64[]")
  107. {
  108. value = Tools.SpitLongArrary(Newtonsoft.Json.JsonConvert.SerializeObject(value).Replace("[", "").Replace("]", "").Trim('"'), ',');
  109. }
  110. else if (ParameterType == "Int32[]")
  111. {
  112. value = Tools.SpitIntArrary(Newtonsoft.Json.JsonConvert.SerializeObject(value).Replace("[", "").Replace("]", "").Trim('"'), ',');
  113. }
  114. else if (ParameterType == "List`1")
  115. {
  116. string val = Newtonsoft.Json.JsonConvert.SerializeObject(value).Replace("[", "").Replace("]", "").Trim('"');
  117. value = Tools.SpitLongArrary(val, ',').ToList();
  118. }
  119. else if(ParameterType == "Nullable`1")
  120. {
  121. string fullName = Function.CheckNull(propertyInfos[i].GetMethod.ReturnParameter.ParameterType.FullName);
  122. if(fullName.Contains("System.Int32"))
  123. {
  124. if(value == null)
  125. {
  126. value = -99;
  127. }
  128. else
  129. {
  130. value = Convert.ToInt32(value);
  131. }
  132. }
  133. }
  134. if(value.ToString() == "-1") value = -1;
  135. if(value.ToString() == "[]") value = "";
  136. propertyInfos[i].SetValue(entry, value, null);
  137. break;
  138. }
  139. }
  140. }
  141. if(context.ActionArguments.ContainsKey(parameterName))
  142. {
  143. context.ActionArguments[parameterName] = entry;
  144. }
  145. else
  146. {
  147. context.ActionArguments.Add(parameterName, entry);
  148. }
  149. }
  150. }
  151. }
  152. }
  153. else
  154. {
  155. string ParamName = context.ActionDescriptor.Parameters[0].Name;
  156. if(context.ActionArguments.ContainsKey(ParamName))
  157. {
  158. context.ActionArguments[ParamName] = Convert.ToInt32(content);
  159. }
  160. else
  161. {
  162. context.ActionArguments.Add(ParamName, Convert.ToInt32(content));
  163. }
  164. }
  165. }
  166. else
  167. {
  168. if(context.ActionDescriptor.Parameters.Count > 0)
  169. {
  170. string ParamName = context.ActionArguments.Keys.First();
  171. object ParamValue = context.ActionArguments.Values.First();
  172. // ParamValue = DesDecrypt(ParamValue.ToString());
  173. if(ParamValue.GetType() == typeof(int))
  174. {
  175. ParamValue = (int)ParamValue;
  176. }
  177. if(context.ActionArguments.ContainsKey(ParamName))
  178. {
  179. context.ActionArguments[ParamName] = ParamValue;
  180. }
  181. else
  182. {
  183. context.ActionArguments.Add(ParamName, ParamValue);
  184. }
  185. }
  186. }
  187. }
  188. string msg = string.Empty;
  189. var values = context.ModelState.Values;
  190. foreach (var item in values)
  191. {
  192. foreach (var err in item.Errors)
  193. {
  194. if (!string.IsNullOrEmpty(msg))
  195. {
  196. msg += " | ";
  197. }
  198. msg += err.ErrorMessage;
  199. }
  200. }
  201. if (!string.IsNullOrEmpty(msg))
  202. {
  203. ApiResult response = new((int)ResultCode.PARAM_ERROR, msg);
  204. context.Result = new JsonResult(response);
  205. }
  206. return base.OnActionExecutionAsync(context, next);
  207. }
  208. /// <summary>
  209. /// OnActionExecuted是在Action中的代码执行之后运行的方法。
  210. /// </summary>
  211. /// <param name="context"></param>
  212. public override void OnResultExecuted(ResultExecutedContext context)
  213. {
  214. if (context.ActionDescriptor is not ControllerActionDescriptor controllerActionDescriptor) return;
  215. //获得注解信息
  216. // LogAttribute logAttribute = GetLogAttribute(controllerActionDescriptor);
  217. // if (logAttribute == null) return;
  218. try
  219. {
  220. string method = context.HttpContext.Request.Method.ToUpper();
  221. // 获取当前的用户
  222. string userName = context.HttpContext.GetName() ?? context.HttpContext.Request.Headers["userName"];
  223. string jsonResult = string.Empty;
  224. if (context.Result is ContentResult result && result.ContentType == "application/json")
  225. {
  226. jsonResult = result.Content.Replace("\r\n", "").Trim();
  227. }
  228. if (context.Result is JsonResult result2)
  229. {
  230. jsonResult = result2.Value?.ToString();
  231. }
  232. //获取当前执行方法的类名
  233. //string className = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
  234. //获取当前成员的名称
  235. //string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
  236. string controller = context.RouteData.Values["Controller"].ToString();
  237. string action = context.RouteData.Values["Action"].ToString();
  238. string ip = HttpContextExtension.GetClientUserIp(context.HttpContext);
  239. // var ip_info = IpTool.Search(ip);
  240. // SysOperLog sysOperLog = new()
  241. // {
  242. // Status = 0,
  243. // OperName = userName,
  244. // OperIp = ip,
  245. // OperUrl = HttpContextExtension.GetRequestUrl(context.HttpContext),
  246. // RequestMethod = method,
  247. // JsonResult = jsonResult,
  248. // OperLocation = HttpContextExtension.GetIpInfo(ip),
  249. // Method = controller + "." + action + "()",
  250. // //Elapsed = _stopwatch.ElapsedMilliseconds,
  251. // OperTime = DateTime.Now,
  252. // OperParam = HttpContextExtension.GetRequestValue(context.HttpContext, method)
  253. // };
  254. // if (logAttribute != null)
  255. // {
  256. // sysOperLog.Title = logAttribute?.Title;
  257. // sysOperLog.BusinessType = (int)logAttribute.BusinessType;
  258. // sysOperLog.OperParam = logAttribute.IsSaveRequestData ? sysOperLog.OperParam : "";
  259. // sysOperLog.JsonResult = logAttribute.IsSaveResponseData ? sysOperLog.JsonResult : "";
  260. // }
  261. LogEventInfo ei = new(NLog.LogLevel.Info, "GlobalActionMonitor", "");
  262. ei.Properties["jsonResult"] = !HttpMethods.IsGet(method) ? jsonResult : "";
  263. // ei.Properties["requestParam"] = sysOperLog.OperParam;
  264. ei.Properties["user"] = userName;
  265. logger.Log(ei);
  266. // OperLogService.InsertOperlog(sysOperLog);
  267. }
  268. catch (Exception ex)
  269. {
  270. logger.Error(ex, $"记录操作日志出错了#{ex.Message}");
  271. }
  272. }
  273. private LogAttribute GetLogAttribute(ControllerActionDescriptor controllerActionDescriptor)
  274. {
  275. var attribute = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
  276. .FirstOrDefault(a => a.GetType().Equals(typeof(LogAttribute)));
  277. return attribute as LogAttribute;
  278. }
  279. private string DesDecrypt(string content)
  280. {
  281. content = HttpUtility.UrlDecode(content);
  282. return Dbconn.DesDecrypt(content, AppSettings.GetConfig("ApiKey"));
  283. }
  284. }
  285. }