我正在尝试使用FileStreamResult
-发送一个大文件
return new UnbufferedFileStreamResult(new FileStream(apiResponse.url, FileMode.Open, FileAccess.Read), "text/csv") { FileDownloadName = new FileInfo(apiResponse.url).Name };
是UnbufferedFileStreamResult
:
public class UnbufferedFileStreamResult : FileStreamResult {
public UnbufferedFileStreamResult(Stream fileStream, string contentType) : base(fileStream, contentType) {
}
public override void ExecuteResult(ActionContext context) {
context.HttpContext.DisableOutputBuffering();
base.ExecuteResult(context);
}
}
这似乎适用于达到一定大小的文件,但如果它们变得太大,我会得到以下异常:
System.IO.IOException: Stream was too long.
at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.MemoryStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Http.Extensions.StreamCopyOperation.CopyToAsync(Stream source, Stream destination, Nullable`1 count, Int32 bufferSize, CancellationToken cancel)
at Microsoft.AspNetCore.Mvc.Infrastructure.FileResultExecutorBase.WriteFileAsync(HttpContext context, Stream fileStream, RangeItemHeaderValue range, Int64 rangeLength)
at Microsoft.AspNetCore.Mvc.Infrastructure.FileStreamResultExecutor.ExecuteAsync(ActionContext context, FileStreamResult result)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultAsync(IActionResult result)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResultFilterAsync[TFilter,TFilterAsync]()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, O
FileStreamResultExecutorBase
因此,在它进入 http 输出流之前,它似乎正在将我的文件流复制到内存流中。我的问题是 1)为什么要这样做,2)我怎样才能防止这种行为,以及 3)是否有这样的结果实现FileStreamResult
可以直接从输入流读取到输出流而无需先复制到内存?