c#/.net HttpContext.Request.BodyReader(PipeReader)的读取方式
public async Task<string> GetString()
{
// 防止中间件已经读取过数据
Request.Body.Position = 0;
do
{
ReadResult readResult = await Request.BodyReader.ReadAsync();
try
{
if (readResult.IsCompleted || readResult.IsCanceled)
{
if (readResult.Buffer.Length <= 0)
{
throw new Exception("Request body is empty.");
}
if (readResult.IsCanceled)
{
throw new Exception("Request body is canceled.");
}
return Encoding.UTF8.GetString(readResult.Buffer);
}
}
finally
{
Request.BodyReader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.End);
}
} while (true);
}