GlobalActionMonitor.cs 9.9 KB

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