GlobalActionMonitor.cs 12 KB

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