asp.net core 修改response的body的内容

第一种简单方式(如果流过大出问题不负责任)

app.Use(async (context, next) =>
{
	// 保持原来的流
	var originalBody = context.Response.Body;

	// 用ms替换当前的流
	var ms = new MemoryStream();
	context.Response.Body = ms;

	await next();
	
	// 替换其中的内容
	ms.Seek(0, SeekOrigin.Begin);
	var reader = new StreamReader(ms);
	var str = reader.ReadToEnd();
	var doubleStr = str+str;
	var buffer = Encoding.UTF8.GetBytes(doubleStr );

	var ms2 = new MemoryStream();
	ms2.Write(buffer, 0, buffer.Length);
	ms2.Seek(0, SeekOrigin.Begin);

	// 写入到原有的流中
	await ms2.CopyToAsync(originalBody);
});

第二种方式参考Response Compression
https://github.com/dotnet/aspnetcore/blob/v3.1.7/src/Middleware/ResponseCompression/src/ResponseCompressionMiddleware.cs

posted @ 2020-08-25 13:12  whyfate  阅读(2216)  评论(0编辑  收藏  举报