RequestMiddleware.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using Microsoft.AspNetCore.Http;
  2. using Newtonsoft.Json;
  3. using NPOI.SS.Formula.Functions;
  4. using Ropin.Inspection.Model;
  5. using System;
  6. using System.Threading.Tasks;
  7. namespace Ropin.Inspection.Api.Filters
  8. {
  9. /// <summary>
  10. /// 请求记录中间件
  11. /// </summary>
  12. public class RequestMiddleware
  13. {
  14. private readonly RequestDelegate _next;
  15. private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(RequestMiddleware));
  16. public RequestMiddleware(RequestDelegate next)
  17. {
  18. this._next = next;
  19. }
  20. public RequestMiddleware() { }
  21. public async Task Invoke(HttpContext httpContext)
  22. {
  23. //启用读取request
  24. httpContext.Request.EnableBuffering();
  25. var request = httpContext.Request;
  26. //请求接口
  27. var reqUrl = request.Path;
  28. //请求参数
  29. var querys= request.Query;
  30. object bodyData = null;
  31. // 检查请求内容类型是否为 application/json
  32. if (request.ContentType?.StartsWith("application/json", StringComparison.OrdinalIgnoreCase) == true)
  33. {
  34. try
  35. {
  36. // 重置请求体流的位置
  37. request.Body.Position = 0;
  38. using (var reader = new System.IO.StreamReader(request.Body, System.Text.Encoding.UTF8, true, 1024, true))
  39. {
  40. var body = await reader.ReadToEndAsync();
  41. // 反序列化 JSON 数据
  42. bodyData = JsonConvert.DeserializeObject(body);
  43. }
  44. // 再次重置请求体流的位置,以便后续中间件或控制器能读取
  45. request.Body.Position = 0;
  46. }
  47. catch (Exception ex)
  48. {
  49. log.Error($"读取请求体时出错: {ex.Message}", ex);
  50. }
  51. }
  52. // 输出日志时包含请求体数据
  53. var logParams = new System.Collections.Generic.Dictionary<string, object>();
  54. foreach (var item in querys)
  55. {
  56. logParams[item.Key] = item.Value.ToString();
  57. }
  58. if (bodyData != null)
  59. {
  60. logParams["RequestBody"] = bodyData;
  61. }
  62. //
  63. Console.WriteLine(reqUrl);
  64. log.Info($"路径3:{reqUrl}");
  65. //log.Info($"路径3:{reqUrl};参数:【{JsonConvert.SerializeObject(logParams)}】");
  66. await _next(httpContext);
  67. }
  68. }
  69. }