GlobalActionMonitor.cs 12 KB

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