从 C# .NetCore 返回 FileStreamResult 时无法访问已关闭的流 API
Cannot access a closed Stream when returning FileStreamResult from C# .NetCore API
C# .Net-Core 3.1
在我的 C# 中 api 我在 FileStreamResult 中返回一个 pdf 文件,效果很好。
通常我在使用中包装流,但是这段代码失败了
Cannot access a closed Stream
.
using (MemoryStream stream = new MemoryStream(byteArray))
{
fileStreamResult = new FileStreamResult(stream, "application/pdf");
}
return (ActionResult)fileStreamResult;
所以我需要这样做:
var stream = new MemoryStream(byteArray);
fileStreamResult = new FileStreamResult(stream, "application/pdf");
return (ActionResult)fileStreamResult;
我假设流需要保持打开状态,我应该担心内存泄漏还是 IIS 会关闭流?有更好的选择吗?
为什么要在 using 块之外保留 return (ActionResult)fileStreamResult;
?
Using 语句关闭并从 using 语句中设置的内存中卸载变量,这就是为什么您在尝试访问已关闭的内存流时遇到错误。如果你只是想 return 最后的结果,你不需要使用 using 语句。
Using 语句对于从内存中删除数据很有用,但您始终可以使用 .dispose()
自己处理数据
C# .Net-Core 3.1
在我的 C# 中 api 我在 FileStreamResult 中返回一个 pdf 文件,效果很好。
通常我在使用中包装流,但是这段代码失败了
Cannot access a closed Stream
.
using (MemoryStream stream = new MemoryStream(byteArray))
{
fileStreamResult = new FileStreamResult(stream, "application/pdf");
}
return (ActionResult)fileStreamResult;
所以我需要这样做:
var stream = new MemoryStream(byteArray);
fileStreamResult = new FileStreamResult(stream, "application/pdf");
return (ActionResult)fileStreamResult;
我假设流需要保持打开状态,我应该担心内存泄漏还是 IIS 会关闭流?有更好的选择吗?
为什么要在 using 块之外保留 return (ActionResult)fileStreamResult;
?
Using 语句关闭并从 using 语句中设置的内存中卸载变量,这就是为什么您在尝试访问已关闭的内存流时遇到错误。如果你只是想 return 最后的结果,你不需要使用 using 语句。
Using 语句对于从内存中删除数据很有用,但您始终可以使用 .dispose()
自己处理数据