response.Body.Seek(0, SeekOrigin.Begin);
string text = await new StreamReader(response.Body).ReadToEndAsync();
text = CustomRes(text);
response.Body.Seek(0, SeekOrigin.Begin);
The problem is, you are changing
a copy of the response. The data in the underlying stream is never changed.
If you want to send your modified response back to the client, then you need to change the data that you send back:
public async Task InvokeAsync(HttpContext context)
{
context.Request.EnableBuffering();
var builder = new StringBuilder();
var request = await FormatRequest(context.Request);
builder.Append("Request: ").AppendLine(request);
builder.AppendLine("Request headers:");
foreach (var header in context.Request.Headers)
{
builder.Append(header.Key).Append(':').AppendLine(header.Value);
}
var originalBodyStream = context.Response.Body;
using var cachedResponseBody = new MemoryStream();
context.Response.Body = cachedResponseBody;
await _next(context);
using var modifiedResponseBody = new MemoryStream();
string response = await ModifyResponse(context.Response, modifiedResponseBody);
builder.Append("Response: ").AppendLine(response);
builder.AppendLine("Response headers: ");
foreach (var header in context.Response.Headers)
{
builder.Append(header.Key).Append(':').AppendLine(header.Value);
}
_logger.LogInformation(builder.ToString());
await modifiedResponseBody.CopyToAsync(originalBodyStream);
}
private async Task<string> ModifyResponse(HttpResponse response, Stream modifiedResponseBody)
{
response.Body.Seek(0, SeekOrigin.Begin);
string text = await new StreamReader(response.Body).ReadToEndAsync();
text = CustomRes(text);
using (var writer = new StreamWriter(modifiedResponseBody))
{
writer.Write(text);
writer.Flush();
}
modifiedResponseBody.Seek(0, SeekOrigin.Begin);
return $"{response.StatusCode}: {text}";
}