GlobalActionMonitor.cs 14 KB

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