GlobalActionMonitor.cs 11 KB

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