代码如下:
using (StreamWriter writer = process.StandardInput) { Request.Body.CopyTo(writer.BaseStream); if(_env.IsDevelopment()) { Console.WriteLine("Request.Body:"); Request.Body.Position = 0; Request.Body.CopyTo(Console.OpenStandardOutput()); } }
在执行至 Request.Body.Position=0 时出错:
System.NotSupportedException: Specified method is not supported. at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.FrameRequestStream.set_Position(Int64 value)
借助MemoryStream解决了这个问题,先将Request.Body复制到MemoryStream,然后从MemoryStream读取。
using (var buffer = new MemoryStream()) { Request.Body.CopyTo(buffer); buffer.Position = 0; buffer.CopyTo(writer.BaseStream); Console.WriteLine("Request.Body:"); buffer.Position = 0; buffer.CopyTo(Console.OpenStandardOutput()); }
ASP.NET Core 2.0 中已经针对这个问题提供了解决方法 —— Request.EnableRewind();
,详见 ASP.NET Core 中读取 Request.Body 的正确姿势
Response).Body).CanRead=false 很郁闷 请教一下这个怎么处理 一直是 不能读 OnActionExecuting OnActionExecuted都是这样
if (httpContent.Request.Body.CanRead)
{
var memery = new System.IO.MemoryStream();
httpContent.Request.Body.CopyTo(memery);
memery.Position = 0;
log.Content = new System.IO.StreamReader(memery, System.Text.UTF8Encoding.UTF8).ReadToEnd();
memery.Position = 0;
httpContent.Request.Body = memery;
}