GlobalActionMonitor.cs 12 KB

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