c# - ASP.NET Core 3.1 在HttpPut请求中读取流文件上传问题
问题描述
问题陈述:
我正在尝试使用 Request.Body 流在 HttpPut 请求中迭代流式文件上传,但我遇到了真正的困难,而且我的 google-fu 几乎没有出现。情况是我希望这样的事情能够奏效,但它不会:
[HttpPut("{accountName}/{subAccount}/{revisionId}/{randomNumber}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> PutTest()
{
var memStream = new MemoryStream();
var b = new Memory<byte>();
int totalBytes = 0;
int bytesRead = 0;
byte[] buffer = new byte[1024];
do
{
bytesRead = await Request.Body.ReadAsync(new Memory<byte>(buffer), CancellationToken.None);
totalBytes += bytesRead;
await memStream.WriteAsync(buffer, 0, bytesRead);
} while (bytesRead > 0);
return Ok(memStream);
}
在调试器中,我可以检查 Request.Body 并查看它的 internal _buffer
。它包含所需的数据。上面的代码运行时,MemoryStream
全是零。在“读取”期间,缓冲区也充满了零。Request.Body 的长度也为 0。
目标:
使用 HttpPut 请求通过流式传输上传文件,以块的形式对其进行迭代,进行一些处理,然后使用 gRPC 将这些块流式传输到另一个端点。我想避免将整个文件读入内存。
我试过的:
这有效:
using (var sr = new StreamReader(Request.Body))
{
var body = await sr.ReadToEndAsync();
return Ok(body);
}
该代码会将所有 Stream 作为字符串读入内存,这是非常不可取的,但它向我证明,可以在我正在处理的方法中以某种方式读取 Request.Body 数据。
在 Startup.cs 类的 configure 方法中,我包含以下内容以确保启用缓冲:
app.Use(async (context, next) => {
context.Request.EnableBuffering();
await next();
});
我曾尝试将 Request.Body 封装在另一个流中,例如BufferedStream
andFileBufferingReadStream
并且那些没有任何区别。
我试过了:
var reader = new BinaryReader(Request.Body, Encoding.Default);
do
{
bytesRead = reader.Read(buffer, 0, buffer.Length);
await memStream.WriteAsync(buffer);
} while (bytesRead > 0);
这也出现了MemoryStream
全零的 a。
解决方案
在我当前的项目中,我经常使用这种请求正文流。
这对我来说非常好:
[HttpPut("{accountName}/{subAccount}/{revisionId}/{randomNumber}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> PutTest(CancellationToken cancel) {
using (var to = new MemoryStream()) {
var from = HttpContext.Request.Body;
var buffer = new byte[8 * 1024];
long totalBytes = 0;
int bytesRead;
while ((bytesRead = await from.ReadAsync(buffer, 0, buffer.Length, cancel)) > 0) {
await to.WriteAsync(buffer, 0, bytesRead, cancel);
totalBytes += bytesRead;
}
return Ok(to);
}
}
我做的唯一不同的事情是:
- 我正在
MemoryStream
范围上下文中创建(使用)。 - 我正在使用稍大的缓冲区(一些试验和错误使我达到了这个特定的大小)
- 我正在使用不同的重载
Stream.ReadAsync
,其中我将bytes[]
缓冲区、读取长度和读取起始位置传递为 0。
推荐阅读
- android-studio - 为什么警报对话框每次都会使我的应用程序崩溃
- javascript - 验证具有不同属性的 json 对象
- sql - SQL join 用先前的值填充空值
- haproxy - 在一次重定向中将 www 重定向到非 www 并将 http 重定向到 https?
- google-cloud-platform - terraform create pub/sub on gcp 给出错误
- django - 如何使用包装类/装饰器在 python django 中传递错误日志记录参数并将其用于每个方法?
- machine-learning - HDBSCAN参数之间的差异
- python - 在 Python 3.x 中使用 os.walk 和 shutil.move 第一个文件夹消失(但文件在剩余中)的问题
- javascript - 使用对象 id 每 10 秒对对象的 javascript 数组进行洗牌
- javascript - 将公司和联系人数组组合成由第三个数组排序的单个结果