GlobalActionMonitor.cs 11 KB

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