TrafficMiddleware.cs
1.94 KB
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
using HHECS.DAQServer.Services;
using HHECS.DAQShared.Models;
namespace HHECS.DAQServer.Middlewares
{
public class TrafficMiddleware
{
private readonly RequestDelegate _next;
private readonly DataCacheService _dataCacheService;
public TrafficMiddleware(RequestDelegate next, DataCacheService dataCacheService)
{
_next = next;
_dataCacheService = dataCacheService;
}
public async Task InvokeAsync(HttpContext context)
{
_ = Guid.TryParse(context.Request.Headers["ClientId"], out var clientId);
// 请求之前
var requestSize = context.Request.ContentLength ?? 0;
// 创建一个流来保存响应
var originalBodyStream = context.Response.Body;
using var newBodyStream = new MemoryStream();
context.Response.Body = newBodyStream;
// 继续处理请求
await _next(context);
// 响应完成后获取响应数据长度
newBodyStream.Seek(0, SeekOrigin.Begin);
var responseSize = newBodyStream.Length;
// 记录流量数据
var record = new TrafficRecord
{
Origin = $"{context.Request.Scheme}://{context.Request.Host.Value}",
RequestPath = context.Request.Path,
Method = context.Request.Method,
RemoteIpAddress = context.Connection.RemoteIpAddress.ToString(),
UserAgent = context.Request.Headers.UserAgent,
RequestSize = requestSize,
ResponseSize = responseSize,
ClientId = clientId,
Created = DateTime.Now,
};
_dataCacheService.TrafficRecords.Enqueue(record);
// 将流复制回原始响应流
newBodyStream.Seek(0, SeekOrigin.Begin);
await newBodyStream.CopyToAsync(originalBodyStream);
}
}
}