From d9c99e0480b4910cdb134778dd5c314b35ec4cf2 Mon Sep 17 00:00:00 2001 From: dengjunjie <dengjunjie@hnkhzn.com> Date: 星期一, 29 九月 2025 10:05:23 +0800 Subject: [PATCH] 1 --- 项目代码/WMS/WIDESEA_WMSServer/WIDESEA_Core/Middlewares/ApiLogMiddleware.cs | 184 +++++++++++++++++++++++++++++++++------------- 1 files changed, 132 insertions(+), 52 deletions(-) diff --git "a/\351\241\271\347\233\256\344\273\243\347\240\201/WMS/WIDESEA_WMSServer/WIDESEA_Core/Middlewares/ApiLogMiddleware.cs" "b/\351\241\271\347\233\256\344\273\243\347\240\201/WMS/WIDESEA_WMSServer/WIDESEA_Core/Middlewares/ApiLogMiddleware.cs" index ee5bdd9..01f7441 100644 --- "a/\351\241\271\347\233\256\344\273\243\347\240\201/WMS/WIDESEA_WMSServer/WIDESEA_Core/Middlewares/ApiLogMiddleware.cs" +++ "b/\351\241\271\347\233\256\344\273\243\347\240\201/WMS/WIDESEA_WMSServer/WIDESEA_Core/Middlewares/ApiLogMiddleware.cs" @@ -1,9 +1,11 @@ 锘縰sing Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; +using Org.BouncyCastle.Asn1.Ocsp; using System; using System.Collections.Generic; using System.Linq; +using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; @@ -21,27 +23,63 @@ /// /// </summary> private readonly RequestDelegate _next; + private readonly ILogger<ApiLogMiddleware> _logger; - public ApiLogMiddleware(RequestDelegate next) + public ApiLogMiddleware(RequestDelegate next, ILogger<ApiLogMiddleware> logger) { _next = next; + _logger = logger; } //todo public async Task InvokeAsync(HttpContext context) { + //if (App.ExpDateTime != null) + //{ + // if ((DateTime.Now - App.ExpDateTime.GetValueOrDefault()).TotalSeconds > 0) + // { + // await ReturnExpiredResponse(context, "绯荤粺宸茶繃鏈燂紝璇疯仈绯荤鐞嗗憳"); + // return; + // } + // //var Hours = (App.ExpDateTime.GetValueOrDefault() - DateTime.Now).TotalHours; + // //if (Hours < 72) + // //{ + // // // 璁板綍璀﹀憡鏃ュ織 + // // _logger.LogWarning($"绯荤粺鍗冲皢鍒版湡锛屽墿浣欐椂闂达細{Hours:F2}灏忔椂锛屽埌鏈熸椂闂达細{App.ExpDateTime.GetValueOrDefault():yyyy-MM-dd HH:mm:ss}"); + + // // // 鍦ㄥ搷搴斿ご涓坊鍔犲埌鏈熸彁绀� + // // context.Response.Headers.Add("X-Expiration-Warning", + // // $"绯荤粺灏嗗湪 {Hours:F2} 灏忔椂鍚庡埌鏈� ({App.ExpDateTime.GetValueOrDefault():yyyy-MM-dd HH:mm:ss})"); + + // // // 濡傛灉闇�瑕佺洿鎺ヨ繑鍥炴彁绀轰俊鎭紝鍙栨秷涓嬮潰鐨勬敞閲� + // // await ReturnExpirationWarningResponse(context, Hours); + // // return; + // //} + + //} + // 杩囨护锛屽彧鏈夋帴鍙� if (context.Request.Path.Value?.Contains("api") ?? false) { + if (App.ExpDateTime != null) + { + if ((DateTime.Now - App.ExpDateTime.GetValueOrDefault()).TotalSeconds > 0 && !context.Request.Path.Value.Contains("getVierificationCode") && context.Request.Path.Value != "/api/User/login") + { + await ReturnExpiredResponse(context, "绯荤粺宸茶繃鏈燂紝璇疯仈绯荤鐞嗗憳"); + return; + } + } context.Request.EnableBuffering(); Stream originalBody = context.Response.Body; - + string requestParam = string.Empty; + string responseParam = string.Empty; try { + (context.RequestServices.GetService(typeof(RequestLogModel)) as RequestLogModel).RequestDate = DateTime.Now; try { // 瀛樺偍璇锋眰鏁版嵁 - await RequestDataLog(context); + requestParam = RequestDataLog(context); context.Request.Body.Position = 0; } catch { } @@ -53,18 +91,19 @@ try { // 瀛樺偍鍝嶅簲鏁版嵁 - ResponseDataLog(context.Response, ms); + responseParam = ResponseDataLog(context.Response); } catch { } ms.Position = 0; await ms.CopyToAsync(originalBody); - + if (!ShouldSkipLogging(context.Request.Path.Value)) + Logger.Add(requestParam, responseParam); } catch (Exception ex) { // 璁板綍寮傚父 - + } finally { @@ -77,61 +116,102 @@ } } + /// <summary> + /// 杩斿洖杩囨湡鍝嶅簲 + /// </summary> + private async Task ReturnExpiredResponse(HttpContext context, string message) + { + context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + context.Response.ContentType = "application/json; charset=utf-8"; + context.Response.Headers.ContentType= "application/json; charset=utf-8"; + var json = new WebResponseContent + { + Message = message, + Code = 500 + }; - private async Task RequestDataLog(HttpContext context) + var jsonString = JsonConvert.SerializeObject(json); + await context.Response.WriteAsync(jsonString); + } + /// <summary> + /// 杩斿洖鍒版湡璀﹀憡鍝嶅簲锛堝彲閫夛級 + /// </summary> + private async Task ReturnExpirationWarningResponse(HttpContext context, double hoursRemaining) + { + context.Response.StatusCode = (int)HttpStatusCode.OK; + context.Response.ContentType = "application/json"; + + var expirationDate = App.ExpDateTime.GetValueOrDefault(); + var response = new + { + Code = 200, + Message = "绯荤粺鍗冲皢鍒版湡璀﹀憡", + Data = new + { + HoursRemaining = hoursRemaining, + ExpirationDate = expirationDate, + FormattedMessage = $"绯荤粺灏嗗湪 {Math.Ceiling(hoursRemaining)} 灏忔椂鍚庡埌鏈燂紝鍒版湡鏃堕棿锛歿expirationDate:yyyy-MM-dd HH:mm:ss}銆傝鑱旂郴绠$悊鍛樼画鏈熴��" + }, + Warning = true + }; + + var jsonString = JsonConvert.SerializeObject(response); + await context.Response.WriteAsync(jsonString); + } + + /// <summary> + /// 鍒ゆ柇鏄惁璺宠繃鏃ュ織璁板綍 + /// </summary> + private bool ShouldSkipLogging(string path) + { + if (string.IsNullOrEmpty(path)) return false; + + var skipKeywords = new[] { "get", "Get", "query", "Query", "DownLoadApp", "downLoadApp", "UploadApp", "uploadApp" }; + return skipKeywords.Any(keyword => path.Contains(keyword, StringComparison.OrdinalIgnoreCase)); + } + + private string RequestDataLog(HttpContext context) { var request = context.Request; + var sr = new StreamReader(request.Body); - //long length = request.Body.Length; - RequestLogInfo requestResponse = new RequestLogInfo() - { - Path = request.Path, - QueryString = request.QueryString.ToString(), - BodyData = await sr.ReadToEndAsync() - }; - var content = JsonConvert.SerializeObject(requestResponse); - if (!string.IsNullOrEmpty(content)) - { - LogLock.OutLogAOP("鎺ュ彛鏃ュ織", new string[] { "璇锋眰鏁版嵁 - 璇锋眰鏁版嵁绫诲瀷:" + requestResponse.GetType().ToString(), content }); - request.Body.Position = 0; - } - } - private void ResponseDataLog(HttpResponse response, MemoryStream ms) - { - ms.Position = 0; - var responseBody = new StreamReader(ms).ReadToEnd(); - - // 鍘婚櫎 Html - var reg = "<[^>]+>"; - var isHtml = Regex.IsMatch(responseBody, reg); - - if (!string.IsNullOrEmpty(responseBody)) + object obj; + string bodyData = sr.ReadToEndAsync().Result; + if (request.ContentLength <= 100000) { - Parallel.For(0, 1, e => + obj = new { - LogLock.OutLogAOP("鎺ュ彛鏃ュ織", new string[] { "鍝嶅簲鏁版嵁 - 鍝嶅簲鏁版嵁绫诲瀷:" + responseBody.GetType().ToString(), responseBody }); - - }); + QueryString = request.QueryString.ToString(), + BodyData = bodyData + }; } + else + { + obj = new + { + QueryString = request.QueryString.ToString(), + BodyData = "" + }; + } + string data = JsonConvert.SerializeObject(obj); + + request.Body.Position = 0; + + return data; } - } - public class RequestLogInfo - { - /// <summary> - /// 璇锋眰鍦板潃 - /// </summary> - public string Path { get; set; } - - /// <summary> - /// 璇锋眰鍙傛暟 - /// </summary> - public string QueryString { get; set; } - - /// <summary> - /// Body鍙傛暟 - /// </summary> - public string BodyData { get; set; } + private string ResponseDataLog(HttpResponse response) + { + if (response.ContentLength <= 100000) + { + response.Body.Position = 0; + using StreamReader stream = new StreamReader(response.Body, leaveOpen: true); + string body = stream.ReadToEnd(); + response.Body.Position = 0; + return body; + } + return ""; + } } } -- Gitblit v1.9.3