[Core 2.1] HttpContext.Response.Body is empty when trying to read it
I'm implementing a custom middleware in Core 2.1 that simply logs all the requests & responses to .txt file. I've followed multiple blogs/articles that show how to read from the stream but somehow none of them seems to be working for me.
public async Task Invoke(HttpContext context) { var originalBodyStream = context.Response.Body; using (var responseBody = new MemoryStream()) { context.Response.Body = responseBody; await _next(context); //responseBodyAsString is ALWAYS empty/"" string responseBodyAsString = await FormatResponse(context.Response); WriteToFile(responseBodyAsString); if (context.Response.StatusCode != 204) await responseBody.CopyToAsync(originalBodyStream); } }
And this is the method that generates the string from the response:
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: {text}"; }
The text variable here is always empty ("").
WriteToFile method simply writes a provided string to a file:
private void AddText(FileStream fs, string value) { byte[] info = new System.Text.UTF8Encoding(true).GetBytes(value); fs.Write(info, 0, info.Length); } private void WriteToFile(string responseBodyAsText) { string dt = DateTime.Now.ToString("hh_mm_ss"); string path = Path.Combine(_env.ContentRootPath, $"Logs/{dt}"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string filePath = Path.Combine(_env.ContentRootPath, $"Logs/{dt}/{dt}.txt"); using (FileStream fs = File.Create(filePath)) { AddText(fs, responseBodyAsText); } }
I have tried following these solutions:
- Log ASP.NET Core Request & Response using middleware
- Log Request & Response in ASP.NET Core
-
but none of them work for me, I always get empty response on all of them. What am I doing wrong?
By empty I meant that the part where the response is supposed to be in the txt file is empty. The text file looks like this:
Response: and that's it, nothing after that hardcoded response string.
0 comments:
Post a Comment