From 02bd4e83750d86ffb45cf38136b707a4a2851245 Mon Sep 17 00:00:00 2001 From: Xin Yan Date: Tue, 30 Jul 2019 10:21:22 -0700 Subject: [PATCH] RequestLoggingMiddleware is not aware certain HTTP response can not carry body. Setting body on HTTP status such as 204 will cause exception. This repros today already by going through a bike renting flow and examine the logs of Gateway container. If running under a debugger, the exception will fail the request. Fix the issue by skipping setting HTTP body for 204, 205 and 304. This is what asp.net core checks in AspNetCore\src\Servers\Kestrel\Core\src\Internal\Http\ HttpProtocol.cs. --- .../Gateway/Middleware/RequestLoggingMiddleware.cs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/samples/BikeSharingApp/Gateway/Middleware/RequestLoggingMiddleware.cs b/samples/BikeSharingApp/Gateway/Middleware/RequestLoggingMiddleware.cs index 623fdfbb0..31236bc09 100644 --- a/samples/BikeSharingApp/Gateway/Middleware/RequestLoggingMiddleware.cs +++ b/samples/BikeSharingApp/Gateway/Middleware/RequestLoggingMiddleware.cs @@ -30,12 +30,18 @@ public async Task Invoke(HttpContext context) await this._next(context); context.Response.Body = responseStream; - memStream.Seek(0, SeekOrigin.Begin); - using (StreamReader reader = new StreamReader(memStream)) + // Writing to response body is not supported for 204, 205 and 304 responses. + if (context.Response.StatusCode != 204 /* NoContent */ && + context.Response.StatusCode != 205 /* ResetContent */ && + context.Response.StatusCode != 304 /* NotModified */) { - responseBody = await reader.ReadToEndAsync(); + memStream.Seek(0, SeekOrigin.Begin); + using (StreamReader reader = new StreamReader(memStream)) + { + responseBody = await reader.ReadToEndAsync(); + } + await context.Response.WriteAsync(responseBody); } - await context.Response.WriteAsync(responseBody); } if (context.Response.StatusCode >= 500)