• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

ASP.NETCore-中间件中读取、修改Request.Body、Response.Body

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

参考:
https://www.cnblogs.com/lwqlun/p/10954936.html
https://zablo.net/blog/post/asp-net-core-redis-html-cache/ (缓存)

//这里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);

修改Response.Body

默认的ResponseStream不能读和写操作,更换默认的ResponseStream为MemoryStream,这样就可以对Response输出的内容进行读写操作了

public class ResponseDistributedCacheMiddleware
    {
        protected RequestDelegate _next;

        private ILogger<ResponseDistributedCacheMiddleware> _logger;

        public ResponseDistributedCacheMiddleware(RequestDelegate next, ILogger<ResponseDistributedCacheMiddleware> logger)
        {
            this._next = next;
            this._logger = logger;
        }

        public async Task Invoke(HttpContext httpContext)
        {
#if DEBUG
            #region request
            string bodyAsText = null;
            HttpRequest request = httpContext.Request;
            string method = request.Method;

            if (HttpMethods.IsPost(method)  //新增
             || HttpMethods.IsPut(method)   //修改全部
             || HttpMethods.IsPatch(method) //修改部分
            )
            {
                //https://devblogs.microsoft.com/aspnet/re-reading-asp-net-core-request-bodies-with-enablebuffering/
                request.EnableBuffering();//允许多次读取HTTP请求的正文
                using (var reader = new StreamReader(request.Body,
                                                     encoding: Encoding.UTF8,
                                                     detectEncodingFromByteOrderMarks: false,
                                                     leaveOpen: true)
                      )
                {
                    bodyAsText = await reader.ReadToEndAsync();
                    request.Body.Position = 0;
                }
                if (!string.IsNullOrWhiteSpace(bodyAsText))
                {
                    bodyAsText = System.Web.HttpUtility.UrlDecode(bodyAsText);
                }
            }
            #endregion
#endif
            #region response
            HttpResponse response = httpContext.Response;
            var responseOriginalStream = response.Body;
            try
            {
                using (var memoryResponseStream = new MemoryStream())
                {
                    //更换默认的Response流对象
                    response.Body = memoryResponseStream;
                    await _next.Invoke(httpContext);
                    memoryResponseStream.Seek(0, SeekOrigin.Begin);
                    await memoryResponseStream.CopyToAsync(responseOriginalStream);
                }
            }
            catch (Exception e)
            {
                this._logger.LogError(e, "出错啦(┬_┬)");
            }
            finally
            {
                response.Body = responseOriginalStream;
            }
            #endregion

        }

    }

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Asp.Net中使用static取代application发布时间:2022-07-10
下一篇:
ProgrammingMicrosoft®ASP.NET英文版翻译发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap