GlobalActionMonitor.cs 14 KB

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