内容目录
ASP.NET Core Response.Body 默认是 HttpResponseStream,其主要特征是只能追加写,不能读取也不能修改。
所以最根本方法是替换 HttpResponseStream。
随便设置一个中间件,或者将 HttpContext 拿出来,定义变量 context。
替换 Body:
var responseOriginalBody = context.Response.Body;
var memStream = new MemoryStream();
context.Response.Body = memStream;
必须在写入 Response 之前执行这个代码,替换 Stream,否则一切努力都会白费。
执行中间件,获取写入的内容:
await next(context);
获取响应的内容:
memStream.Position = 0;
var responseReader = new StreamReader(memStream, Encoding.UTF8);
var responseBody = await responseReader.ReadToEndAsync();
重新使用 HttpResponseStream,将响应的数据修改后再放到 HttpResponseStream。
// 修改内容,代码省略
memStream.Position = 0;
// 将 memStream 修改后的内容写到 HttpResponseStream
await memStream.CopyToAsync(responseOriginalBody);
context.Response.Body = responseOriginalBody;
// 可以正常追加了
await context.Response.WriteAsync(",上班有三好,好困,好饿,好烦");
完整代码:
// 请求流处理
// 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;
//设置stream存放ResponseBody
var responseOriginalBody = context.Response.Body;
var memStream = new MemoryStream();
context.Response.Body = memStream;
// 执行其他中间件
await next(context);
//处理执行其他中间件后的ResponseBody
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(",上班有三好,好困,好饿,好烦");
文章评论