RecordAPIOperationMiddleware.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. using AlibabaCloud.OpenApiClient.Models;
  2. using Aspose.Words;
  3. using NPOI.HSSF.Record;
  4. using OASystem.API.OAMethodLib;
  5. using OASystem.Domain.Attributes;
  6. using OASystem.Domain.Entities.Customer;
  7. using OASystem.Infrastructure.Repositories.CRM;
  8. using System.ComponentModel.DataAnnotations;
  9. using System.Diagnostics;
  10. using static Google.Protobuf.Reflection.SourceCodeInfo.Types;
  11. using static OASystem.API.OAMethodLib.JWTHelper;
  12. using UAParser;
  13. using System.Collections.Generic;
  14. using XAct;
  15. namespace OASystem.API.Middlewares
  16. {
  17. /// <summary>
  18. /// 指定API操作记录信息
  19. /// </summary>
  20. public class RecordAPIOperationMiddleware
  21. {
  22. private readonly RequestDelegate _next;
  23. private readonly HttpClient _httpClient;
  24. private readonly IConfiguration _config;
  25. private readonly SqlSugarClient _sqlSugar;
  26. public RecordAPIOperationMiddleware(RequestDelegate next, IConfiguration config, HttpClient httpClient, SqlSugarClient sqlSugar)
  27. {
  28. _next = next;
  29. _httpClient = httpClient;
  30. _config = config;
  31. _sqlSugar = sqlSugar;
  32. }
  33. public async Task InvokeAsync(HttpContext context)
  34. {
  35. // 启用请求体流的缓冲,允许多次读取
  36. context.Request.EnableBuffering();
  37. // 读取请求体内容
  38. var requestBodyText = await ReadRequestBody(context.Request);
  39. // 检查控制器方法是否使用了自定义属性
  40. var endpoint = context.GetEndpoint();
  41. var apiLogAttribute = endpoint?.Metadata?.GetMetadata<ApiLogAttribute>();
  42. if (apiLogAttribute != null)
  43. {
  44. var startTime = DateTime.UtcNow;
  45. int portType = 1, userId = 0, id = 0, status = 0;
  46. string updatePreData = string.Empty, updateBefData = string.Empty;
  47. bool param5Bool = false, param6Bool = false;
  48. try
  49. {
  50. userId = await ReadToken(context);
  51. if (!string.IsNullOrEmpty(requestBodyText))
  52. {
  53. object param1 = string.Empty, param2 = string.Empty, param3 = string.Empty, param4 = string.Empty, param5 = string.Empty, param6 = string.Empty;
  54. var requestBodyJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(requestBodyText);
  55. bool exists1 = requestBodyJson.TryGetValue("portType", out param1);
  56. bool exists2 = requestBodyJson.TryGetValue("userId", out param2);
  57. bool exists3 = requestBodyJson.TryGetValue("currUserId", out param3);
  58. bool exists4 = requestBodyJson.TryGetValue("createUserId", out param4);
  59. bool exists5 = requestBodyJson.TryGetValue("id", out param5);
  60. bool exists6 = requestBodyJson.TryGetValue("status", out param6);
  61. if (!string.IsNullOrEmpty(param1.ToString())) int.TryParse(param1.ToString(), out portType);
  62. //用户Id处理
  63. if (userId < 1)
  64. {
  65. if (apiLogAttribute.OperationEnum == OperationEnum.Login)
  66. {
  67. var number = requestBodyJson?["number"].ToString();
  68. if (!string.IsNullOrEmpty(number))
  69. {
  70. var info = await _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0 && x.Number.Equals(number)).FirstAsync();
  71. userId = info.Id;
  72. }
  73. }
  74. else
  75. {
  76. if (int.TryParse(param2.ToString(), out userId)) { }
  77. else if (int.TryParse(param3.ToString(), out userId)) { }
  78. else if (int.TryParse(param4.ToString(), out userId)) { }
  79. }
  80. }
  81. //编辑前数据查询;
  82. if (param5 != null) if (!string.IsNullOrEmpty(param5.ToString())) param5Bool = int.TryParse(param5.ToString(), out id);
  83. if (param6 != null) if (!string.IsNullOrEmpty(param6.ToString())) param6Bool = int.TryParse(param6.ToString(), out status);
  84. if (param6Bool)
  85. {
  86. // 2 修改
  87. if (status == 2) updatePreData = await TableInfoToJson(apiLogAttribute.TableName, id);
  88. }
  89. else if (param5Bool)
  90. {
  91. // id > 0 修改
  92. if (id > 0) updatePreData = await TableInfoToJson(apiLogAttribute.TableName, id);
  93. }
  94. }
  95. }
  96. catch (JsonException) { }
  97. // 保存原始响应体流
  98. var originalResponseBody = context.Response.Body;
  99. // 创建一个新的内存流来捕获响应体
  100. using var responseMemoryStream = new MemoryStream();
  101. context.Response.Body = responseMemoryStream;
  102. // 调用下一个中间件
  103. await _next(context);
  104. // 重置响应体流的位置
  105. responseMemoryStream.Position = 0;
  106. // 读取响应体内容
  107. var responseBodyText = await ReadResponseBody(responseMemoryStream);
  108. // 将响应体内容写回原始响应体流
  109. await responseMemoryStream.CopyToAsync(originalResponseBody);
  110. //修改后数据查询
  111. if (param6Bool)
  112. {
  113. // 2 修改
  114. if (status == 2) updateBefData = await TableInfoToJson(apiLogAttribute.TableName, id);
  115. }
  116. else if (param5Bool)
  117. {
  118. // id > 0 修改
  119. if (id > 0) updateBefData = await TableInfoToJson(apiLogAttribute.TableName, id);
  120. }
  121. string remoteIp = context.Connection.RemoteIpAddress?.ToString(),
  122. location = string.Empty;
  123. // 检查请求头中的X-Forwarded-For,以获取真实的客户端IP地址
  124. if (context.Request.Headers.ContainsKey("X-Forwarded-For"))
  125. {
  126. remoteIp = context.Request.Headers["X-Forwarded-For"].ToString().Split(',', StringSplitOptions.RemoveEmptyEntries)[0];
  127. }
  128. remoteIp = await GetExternalIp();
  129. location = await GetIpLocation(remoteIp);
  130. string deviceType = string.Empty, browser = string.Empty, os = string.Empty;
  131. var userAgent = context.Request.Headers["User-Agent"].FirstOrDefault();
  132. if (!string.IsNullOrEmpty(userAgent))
  133. {
  134. // 解析User-Agent头
  135. var parser = Parser.GetDefault();
  136. var client = parser.Parse(userAgent);
  137. // 提取浏览器信息
  138. browser = client.UA.Family; // 浏览器名称
  139. var browserVersion = client.UA.Major + "." + client.UA.Minor + "." + client.UA.Patch; // 浏览器版本
  140. browser += $"({browserVersion})";
  141. // 提取操作系统信息
  142. os = client.OS.Family; // 操作系统名称
  143. var osVersion = string.Empty; // 操作系统版本
  144. if (!string.IsNullOrEmpty(client.OS.Major)) osVersion += client.OS.Major ;
  145. if (!string.IsNullOrEmpty(client.OS.Minor)) osVersion += "." + client.OS.Minor;
  146. if (!string.IsNullOrEmpty(client.OS.Patch)) osVersion += "." + client.OS.Patch;
  147. if (!string.IsNullOrEmpty(osVersion)) os += $"({osVersion})";
  148. // 提取设备信息
  149. deviceType = client.Device.Family; // 设备类型,如 'mobile', 'tablet', 'desktop' 等
  150. }
  151. // 记录请求结束时间
  152. var endTime = DateTime.UtcNow;
  153. // 计算耗时
  154. var duration = (long)(endTime - startTime).TotalMilliseconds;
  155. var logInfo = new Crm_TableOperationRecord() {
  156. TableName = apiLogAttribute.TableName,
  157. PortType = portType,
  158. OperationItem = apiLogAttribute.OperationEnum,
  159. DataId = apiLogAttribute.DataId,
  160. RequestUrl = context.Request.Path,
  161. RemoteIp = remoteIp,
  162. Location = location,
  163. RequestParam =!string.IsNullOrEmpty(requestBodyText) ? JsonConvert.SerializeObject(requestBodyText) : null,
  164. ReturnResult = !string.IsNullOrEmpty(responseBodyText) ? JsonConvert.SerializeObject(requestBodyText) : null,
  165. Elapsed = duration,
  166. Status = context.Response.StatusCode.ToString(),
  167. CreateUserId = userId,
  168. UpdatePreData = updatePreData,
  169. UpdateBefData = updateBefData,
  170. Browser= browser,
  171. Os = os,
  172. DeviceType = deviceType,
  173. };
  174. // 存储到数据库
  175. await _sqlSugar.Insertable(logInfo).ExecuteCommandAsync();
  176. }
  177. else
  178. {
  179. await _next(context);
  180. }
  181. }
  182. private async Task<string> TableInfoToJson(string tableName,int id)
  183. {
  184. if (_sqlSugar.DbMaintenance.IsAnyTable(tableName))
  185. {
  186. var info = await _sqlSugar.Queryable<dynamic>(tableName).Where("id=@id", new { id = id }).FirstAsync();
  187. return JsonConvert.SerializeObject(info);
  188. }
  189. return string.Empty;
  190. }
  191. private async Task<string> ReadRequestBody(HttpRequest request)
  192. {
  193. request.EnableBuffering();
  194. using var reader = new StreamReader(
  195. request.Body,
  196. Encoding.UTF8,
  197. detectEncodingFromByteOrderMarks: false,
  198. bufferSize: 8192,
  199. leaveOpen: true
  200. );
  201. var body = await reader.ReadToEndAsync();
  202. request.Body.Position = 0;
  203. return body;
  204. }
  205. private async Task<string> ReadResponseBody(Stream stream)
  206. {
  207. using var reader = new StreamReader(
  208. stream,
  209. Encoding.UTF8,
  210. detectEncodingFromByteOrderMarks: false,
  211. bufferSize: 8192,
  212. leaveOpen: true
  213. );
  214. var body = await reader.ReadToEndAsync();
  215. stream.Position = 0;
  216. return body;
  217. }
  218. private async Task<int> ReadToken(HttpContext context)
  219. {
  220. var authHeader = context.Request.Headers["Authorization"].FirstOrDefault();
  221. // 检查Authorization头是否存在且以"Bearer "开头
  222. if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
  223. {
  224. var authInfo = JwtHelper.SerializeJwt(authHeader);
  225. if (authInfo != null) return authInfo.UserId;
  226. }
  227. return 0;
  228. }
  229. private async Task<string> GetExternalIp()
  230. {
  231. var response = await _httpClient.GetAsync("https://ifconfig.me");
  232. response.EnsureSuccessStatusCode();
  233. return await response.Content.ReadAsStringAsync();
  234. }
  235. private async Task<string> GetIpLocation(string ip)
  236. {
  237. var response = await _httpClient.GetAsync($"https://ipinfo.io/{ip}/json");
  238. response.EnsureSuccessStatusCode();
  239. var json = await response.Content.ReadAsStringAsync();
  240. var ipInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
  241. return $"{ipInfo.country}, {ipInfo.city}";
  242. }
  243. }
  244. }