ASP.NET Core Response.Body is by default an HttpResponseStream, which is characterized by allowing writes only in append mode, and it cannot be read or modified.
Therefore, the fundamental method is to replace the HttpResponseStream.
You can set up a middleware or extract the HttpContext and define a variable context
.
Replace the Body:
var responseOriginalBody = context.Response.Body;
var memStream = new MemoryStream();
context.Response.Body = memStream;
This code must execute before writing to the Response to replace the Stream; otherwise, all efforts will be in vain.
Execute the middleware to obtain the written content:
await next(context);
Get the response content:
memStream.Position = 0;
var responseReader = new StreamReader(memStream, Encoding.UTF8);
var responseBody = await responseReader.ReadToEndAsync();
Reuse HttpResponseStream, modify the response data, and then place it back into HttpResponseStream.
// Modify content, code omitted
memStream.Position = 0;
// Write the modified content from memStream to HttpResponseStream
await memStream.CopyToAsync(responseOriginalBody);
context.Response.Body = responseOriginalBody;
// You can append normally now
await context.Response.WriteAsync(",上班有三好,好困,好饿,好烦");
Complete code:
// Request stream handling
// https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/request-response?view=aspnetcore-6.0
var proxyFeature = context.GetReverseProxyFeature();
var cluster = proxyFeature.Cluster;
var destinations = proxyFeature.AvailableDestinations;
// Set the stream to store ResponseBody
var responseOriginalBody = context.Response.Body;
var memStream = new MemoryStream();
context.Response.Body = memStream;
// Execute other middleware
await next(context);
// Handle the ResponseBody after executing other middleware
memStream.Position = 0;
var responseReader = new StreamReader(memStream, Encoding.UTF8);
var responseBody = await responseReader.ReadToEndAsync();
memStream.Position = 0;
await memStream.CopyToAsync(responseOriginalBody);
context.Response.Body = responseOriginalBody;
await context.Response.WriteAsync(",上班有三好,好困,好饿,好烦");
文章评论