Asp.NetCore3.1 several times to read Request.Body

        // POST: Reg
        [HttpPost]
        public async Task<string> Post()
        {

            //StreamReader sr = new StreamReader(Request.Body);
            //string data = await sr.ReadToEndAsync();

            string data = "";
            using (MemoryStream ms=new MemoryStream())
            {
                await Request.Body.CopyToAsync(ms);
                //设置当前流的位置为0
                ms.Seek(0, SeekOrigin.Begin);
                logger.LogInformation("= ms.Length " + ms.Length);
                 // position after the implementation of this stream will ReadToEnd requestBodyStream from 0 to the last position (i.e. request.ContentLength) 
                Data = new new the StreamReader (MS, Encoding.UTF8) .ReadToEnd (); 
                logger.LogInformation ( " Data = " + Data); 

                // set the position of the current flow is 0 
                ms.Seek ( 0 , SeekOrigin.Begin); 
                request.body = MS; 
                the StreamReader SR = new new the StreamReader (request.body);
                 String = DATA2 the await sr.ReadToEndAsync ();
                logger.LogInformation("data2=" + data2);
            }

            string header = $"请求头:\r\n";
            foreach (var item in Request.Headers)
            {
                header += $"{item.Key}:{item.Value}\r\n";
            }
            logger.LogInformation(header);

            var ip = Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip))
            {
                //ip = Request.HttpContext.Connection.RemoteIpAddress.ToString();
                //ip = Request.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString();
                ip = Request.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            }
            logger.LogInformation("ip=" + ip);

            //...
        }

 

Guess you like

Origin www.cnblogs.com/kevin860/p/12619389.html