ASP.NET Core-修改请求和返回的Body
2021-06-04 13:01
标签:mem str end iter ceo begin 字符 内容 修改 修改请求的Body: 修改返回的Body: ... ASP.NET Core-修改请求和返回的Body 标签:mem str end iter ceo begin 字符 内容 修改 原文地址:https://www.cnblogs.com/fanfan-90/p/12341692.html//这里ReadToEnd执行完毕后requestBodyStream流的位置会从0到最后位置(即request.ContentLength)
var RequestBody = new StreamReader(HttpContext.Request.BodyReader.AsStream()).ReadToEnd();//读取body
byte[] content1 = Encoding.UTF8.GetBytes(RequestBody.Replace("ceo", "CEO"));//替换字符串并且字符串转换成字节
var requestBodyStream = new MemoryStream();//创建一个流
requestBodyStream.Seek(0, SeekOrigin.Begin);//设置从0开始读取
requestBodyStream.Write(content1, 0, content1.Length);//把修改写入流中
HttpContext.Request.Body = requestBodyStream;//把修改后的内容赋值给请求body
HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);
var orgBodyStream = context.Response.BodyWriter.AsStream();//获取body内容
var ms = new MemoryStream();
ms.Seek(0, SeekOrigin.Begin);
using (var sr = new StreamReader(ms))//
{
string newContent = sr.ReadToEnd();
if (newContent.Contains("ceo"))
{
byte[] content = Encoding.UTF8.GetBytes(newContent.Replace("ceo", "CEO"));
ms.Write(content, 0, content.Length);
ms.Seek(0, SeekOrigin.Begin);
}
await ms.CopyToAsync(orgBodyStream);
}
文章标题:ASP.NET Core-修改请求和返回的Body
文章链接:http://soscw.com/index.php/essay/90400.html