hutongqing
2024-10-15 0d07b90fd906e52ce486484aa53a6850983b1325
WIDESEAWCS_Server/WIDESEAWCS_Core/Middlewares/ApiLogMiddleware.cs
@@ -5,6 +5,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using WIDESEAWCS_Core.Helper;
using WIDESEAWCS_Core.LogHelper;
@@ -31,83 +32,81 @@
        //todo
        public async Task InvokeAsync(HttpContext context)
        {
            //if (AppSettings.app("Middleware", "RequestResponseLog", "Enabled").ObjToBool())
            {
                // 过滤,只有接口
                if (context.Request.Path.Value?.Contains("api") ?? false)
                {
                    context.Request.EnableBuffering();
                    //Stream originalBody = context.Response.Body;
                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
                    {
                        // 存储请求数据
                        //string requestParam = GetRequestData(context);
                        //DateTime beginDate = DateTime.Now;
                        //using var ms = new MemoryStream();
                        //context.Response.Body = ms;
                        requestParam = RequestDataLog(context);
                        context.Request.Body.Position = 0;
                    }
                    catch { }
                    using MemoryStream ms = new();
                    context.Response.Body = ms;
                        await _next(context);
                    try
                    {
                        // 存储响应数据
                        //DateTime endDate = DateTime.Now;
                        //string responseParam = GetResponsetData(context);
                        responseParam = ResponseDataLog(context.Response);
                    }
                    catch { }
                        //context.Response.Body.Position = 0;
                        //await context.Response.Body.CopyToAsync(originalBody);
                        //Logger.WriteApiLog2DB(context,requestParam, beginDate, responseParam, endDate, context.Response.StatusCode == 200 ? LoggerStatus.Success : LoggerStatus.Error);
                    ms.Position = 0;
                    await ms.CopyToAsync(originalBody);
                    if (!(context.Request.Path.Value?.Contains("Get") ?? false))
                        Logger.Add(requestParam, responseParam);
                    }
                    catch (Exception ex)
                    {
                        // 记录异常                        
                        _logger.LogError(ex.Message + "" + ex.InnerException);
                    }
                    finally
                    {
                        //context.Response.Body = originalBody;
                    context.Response.Body = originalBody;
                    }
                }
                //else
                //{
                //    await _next(context);
                //}
            }
            //else
            //{
            //    await _next(context);
            //}
        }
        private string GetRequestData(HttpContext context)
            else
        {
            try
            {
                using StreamReader sr = new StreamReader(context.Request.Body);
                string request = JsonConvert.SerializeObject(sr.ReadToEnd()); ;
                context.Request.Body.Position = 0;
                return request;
            }
            catch (Exception ex)
            {
                return $"请求参数获取错误,{ex.Message}";
                await _next(context);
            }
        }
        private string GetResponsetData(HttpContext context)
        private string RequestDataLog(HttpContext context)
        {
            try
            var request = context.Request;
            var sr = new StreamReader(request.Body);
            object obj = new
            {
                using StreamReader sr = new StreamReader(context.Response.Body);
                string response = JsonConvert.SerializeObject(sr.ReadToEnd()); ;
                context.Response.Body.Position = 0;
                return response;
                QueryString = request.QueryString.ToString(),
                BodyData = sr.ReadToEndAsync().Result
            };
            string data = JsonConvert.SerializeObject(obj);
            request.Body.Position = 0;
            return data;
            }
            catch (Exception ex)
        private string ResponseDataLog(HttpResponse response)
            {
                return $"响应参数获取错误,{ex.Message}";
            }
            response.Body.Position = 0;
            using StreamReader stream = new StreamReader(response.Body, leaveOpen: true);
            string body = stream.ReadToEnd();
            response.Body.Position = 0;
            return body;
        }
    }
}