-
Notifications
You must be signed in to change notification settings - Fork 0
/
RequestCatcher.cs
84 lines (77 loc) · 3.36 KB
/
RequestCatcher.cs
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
public class RequestCatcher {
private readonly RequestDelegate _next;
public RequestCatcher(RequestDelegate next) {
_next = next;
}
public async Task InvokeAsync(HttpContext context) {
context.Request.EnableBuffering();
var savedata = new SaveData();
try {
var sw = new Stopwatch();
sw.Start();
var reqId = Guid.NewGuid();
var requestMethod = context.Request.Method;
var requestUri = context.Request.GetDisplayUrl();
using var ms = new MemoryStream();
await context.Request.Body.CopyToAsync(ms);
string requestBody = Encoding.UTF8.GetString(ms.ToArray());
context.Request.Body.Seek(0, SeekOrigin.Begin);
var requestHeader = JsonSerializer.Serialize(context.Request.Headers);
var requestCookies = JsonSerializer.Serialize(context.Request.Cookies);
var requestBytesLength = Encoding.UTF8.GetByteCount(requestBody);
var requestContentType = context.Request.ContentType;
var requestHttps = context.Request.IsHttps;
var requestTrailers = context.Request.CheckTrailersAvailable();
var requestIp = context.Connection.RemoteIpAddress?.ToString() ?? "";
var trace = context.TraceIdentifier;
// Call the next delegate/middleware in the pipeline.
await _next(context);
try {
var responseHeaders = context.Response.Headers;
var responseCookies = context.Response.Cookies;
var responseStatus = context.Response.StatusCode;
var responseContentType = context.Response.ContentType;
await savedata.ResSave(new ResModel {
reqId = reqId,
responseHeaders = responseHeaders.Count > 0 ? JsonSerializer.Serialize(responseHeaders) : "",
responseCookies = JsonSerializer.Serialize(responseCookies),
responseStatus = responseStatus
});
}
catch (Exception exc) {
await savedata.ExceptionSave(exc.Message);
}
var reqElapsed = sw.Elapsed.TotalMilliseconds;
await savedata.ReqSave(new ReqModel {
reqId = reqId,
requestMethod = requestMethod,
requestUri = requestUri,
requestBody = requestBody,
requestHeader = requestHeader,
requestCookies = requestCookies,
requestBytesLength = requestBytesLength,
requestContentType = requestContentType ?? "",
requestHttps = requestHttps,
requestTrailers = requestTrailers,
trace = trace,
requestElapsed = reqElapsed,
clientIp = requestIp
});
sw.Stop();
}
catch (Exception exc) {
await savedata.ExceptionSave(exc.Message);
}
}
}
public static class RequestCatcherMiddlewareExtensions {
/// <summary>
/// method for capturing requests flowing through
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static IApplicationBuilder UseRequestCatcher(
this IApplicationBuilder builder) {
return builder.UseMiddleware<RequestCatcher>();
}
}