using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using NPOI.SS.Formula.Functions; using Ropin.Inspection.Model; using System; using System.Threading.Tasks; namespace Ropin.Inspection.Api.Filters { /// /// 请求记录中间件 /// public class RequestMiddleware { private readonly RequestDelegate _next; private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(RequestMiddleware)); public RequestMiddleware(RequestDelegate next) { this._next = next; } public RequestMiddleware() { } public async Task Invoke(HttpContext httpContext) { //启用读取request httpContext.Request.EnableBuffering(); var request = httpContext.Request; //请求接口 var reqUrl = request.Path; //请求参数 var querys= request.Query; object bodyData = null; // 检查请求内容类型是否为 application/json if (request.ContentType?.StartsWith("application/json", StringComparison.OrdinalIgnoreCase) == true) { try { // 重置请求体流的位置 request.Body.Position = 0; using (var reader = new System.IO.StreamReader(request.Body, System.Text.Encoding.UTF8, true, 1024, true)) { var body = await reader.ReadToEndAsync(); // 反序列化 JSON 数据 bodyData = JsonConvert.DeserializeObject(body); } // 再次重置请求体流的位置,以便后续中间件或控制器能读取 request.Body.Position = 0; } catch (Exception ex) { log.Error($"读取请求体时出错: {ex.Message}", ex); } } // 输出日志时包含请求体数据 var logParams = new System.Collections.Generic.Dictionary(); foreach (var item in querys) { logParams[item.Key] = item.Value.ToString(); } if (bodyData != null) { logParams["RequestBody"] = bodyData; } // Console.WriteLine(reqUrl); log.Info($"路径3:{reqUrl}"); //log.Info($"路径3:{reqUrl};参数:【{JsonConvert.SerializeObject(logParams)}】"); await _next(httpContext); } } }