@@ -15,6 +15,12 @@ internal sealed class RequestLoggingMiddleware(
1515 "/above-board"
1616 ] ;
1717
18+ private static readonly HashSet < string > JsonMediaTypes = new ( StringComparer . OrdinalIgnoreCase )
19+ {
20+ "application/json" ,
21+ "text/json"
22+ } ;
23+
1824 public async Task InvokeAsync ( HttpContext context )
1925 {
2026 if ( HttpMethods . IsOptions ( context . Request . Method ) )
@@ -30,7 +36,12 @@ public async Task InvokeAsync(HttpContext context)
3036 return ;
3137 }
3238
33- var requestLog = await CaptureRequestAsync ( context . Request ) ;
39+ var isJsonRequest = IsJson ( context . Request . ContentType ) ;
40+
41+ var requestLog = isJsonRequest
42+ ? await CaptureRequestAsync ( context . Request )
43+ : ( Headers : "{}" , Body : "[SKIPPED_NON_JSON]" ) ;
44+
3445 var originalBodyStream = context . Response . Body ;
3546
3647 await using var responseBody = new MemoryStream ( ) ;
@@ -46,7 +57,12 @@ public async Task InvokeAsync(HttpContext context)
4657 {
4758 var elapsedMs = Stopwatch . GetElapsedTime ( stopwatch )
4859 . TotalMilliseconds ;
49- var responseLog = await CaptureResponseAsync ( context . Response ) ;
60+
61+ var isJsonReply = IsJson ( context . Response . ContentType ) ;
62+
63+ var responseLog = isJsonReply
64+ ? await CaptureResponseAsync ( context . Response )
65+ : ( Headers : "{}" , Body : "[SKIPPED_NON_JSON]" ) ;
5066
5167 logger . LogInformation (
5268 "[Incoming Request] HTTP {Method} {Query} responded with {StatusCode} in {ElapsedMilliseconds}ms. " +
@@ -95,4 +111,9 @@ public async Task InvokeAsync(HttpContext context)
95111 JsonSerializer . Serialize ( redactedBody )
96112 ) ;
97113 }
114+
115+ private static bool IsJson ( string ? contentType ) =>
116+ ! string . IsNullOrWhiteSpace ( contentType ) &&
117+ ( JsonMediaTypes . Any ( contentType . StartsWith ) ||
118+ contentType . Contains ( "+json" , StringComparison . OrdinalIgnoreCase ) ) ;
98119}
0 commit comments