刘磊
2025-06-09 dabbcafc629ef87d11ba55ef8cc1cdc776c047d8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Core.Helper;
using WIDESEA_Core.LogHelper;
 
namespace WIDESEA_Core.Middlewares
{
    /// <summary>
    /// 记录请求和响应数据
    /// </summary>
    public class ApiLogMiddleware
    {
        /// <summary>
        /// 
        /// </summary>
        private readonly RequestDelegate _next;
        private readonly ILogger<ApiLogMiddleware> _logger;
 
        public ApiLogMiddleware(RequestDelegate next, ILogger<ApiLogMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }
 
        //todo
        public async Task InvokeAsync(HttpContext context)
        {
            //if (AppSettings.app("Middleware", "RequestResponseLog", "Enabled").ObjToBool())
            {
                // 过滤,只有接口
                if (context.Request.Path.Value.Contains("api"))
                {
                    context.Request.EnableBuffering();
                    //Stream originalBody = context.Response.Body;
 
                    try
                    {
                        // 存储请求数据
                        //string requestParam = GetRequestData(context);
                        //DateTime beginDate = DateTime.Now;
 
                        //using var ms = new MemoryStream();
                        //context.Response.Body = ms;
 
                        await _next(context);
 
                        // 存储响应数据
                        //DateTime endDate = DateTime.Now;
                        //string responseParam = GetResponsetData(context);
 
                        //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);
                    }
                    catch (Exception ex)
                    {
                        // 记录异常                        
                        _logger.LogError(ex.Message + "" + ex.InnerException);
                    }
                    finally
                    {
                        //context.Response.Body = originalBody;
                    }
                }
                //else
                //{
                //    await _next(context);
                //}
            }
            //else
            //{
            //    await _next(context);
            //}
        }
 
        private string GetRequestData(HttpContext context)
        {
            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}";
            }
        }
 
        private string GetResponsetData(HttpContext context)
        {
            try
            {
                using StreamReader sr = new StreamReader(context.Response.Body);
                string response = JsonConvert.SerializeObject(sr.ReadToEnd()); ;
                context.Response.Body.Position = 0;
                return response;
            }
            catch (Exception ex)
            {
                return $"响应参数获取错误,{ex.Message}";
            }
        }
    }
}