GlobalActionMonitor.cs 14 KB

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