-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathRequestResponseLoggingMiddleware.cs
51 lines (41 loc) · 1.66 KB
/
RequestResponseLoggingMiddleware.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
using Serilog;
namespace LearnSmartCoding.CosmosDb.Linq.API
{
public class RequestResponseLoggingMiddleware
{
private readonly RequestDelegate _next;
public RequestResponseLoggingMiddleware(RequestDelegate next
)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
// Log the request
Log.Information($"Request: {context.Request.Method} {context.Request.Path}");
// Copy the original response body stream
var originalBodyStream = context.Response.Body;
// Create a new memory stream to capture the response
using (var responseBody = new MemoryStream())
{
// Set the response body stream to the memory stream
context.Response.Body = responseBody;
// Continue processing the request
await _next(context);
// Log the response
var response = await FormatResponse(context.Response);
Log.Information($"Response: {response}");
// Copy the captured response to the original response body stream
responseBody.Seek(0, SeekOrigin.Begin);
await responseBody.CopyToAsync(originalBodyStream);
}
}
private async Task<string> FormatResponse(HttpResponse response)
{
response.Body.Seek(0, SeekOrigin.Begin);
var text = await new StreamReader(response.Body).ReadToEndAsync();
response.Body.Seek(0, SeekOrigin.Begin);
return $"{response.StatusCode}: {text}";
}
}
}