C#使用语句创建流对象
我有一种方法下载s3文件 方法C#使用语句创建流对象,c#,asp.net-mvc,amazon-s3,io,C#,Asp.net Mvc,Amazon S3,Io,我有一种方法下载s3文件 方法 Public ActionResult download(string filename, string credentials) { .... Using(stream res = response from s3) { return file(res, type, filename); } } 但执行上述方法时抛出异常 异常消息-请求被中止:连接意外关闭 下载后,我必须释放流“res”对象。如果使用文件方法返回操作结果,您将
Public ActionResult download(string filename, string credentials)
{
....
Using(stream res = response from s3)
{
return file(res, type, filename);
}
}
但执行上述方法时抛出异常
异常消息-请求被中止:连接意外关闭
下载后,我必须释放流“res”对象。如果使用
文件
方法返回操作结果
,您将将关闭流的责任转移到操作结果上,因此,您确实不想调用Dispose
或使用using
。这使得ActionResult
不需要缓冲数据。因此:只需使用取出:
public ActionResult Download(string filename, string credentials)
{
....
var res = /* response from s3 */
return File(res, type, filename);
}
如果您有非平凡的代码,可以使其更复杂:
public ActionResult Download(string filename, string credentials)
{
....
Stream disposeMe = null;
try {
// ...
disposeMe = /* response from s3 */
// ...
var result = File(disposeMe, type, filename);
disposeMe = null; // successfully created File result which
// now owns the stream, so *leave stream open*
return result;
} finally {
disposeMe?.Dispose(); // if not handed over, dispose
}
}
s3的响应是什么?
?大小为50 MB的Zip文件不,不,不,方法/函数/对象/数据类型/任何东西到底是什么?它是字节,我们将字节转换为流以在浏览器中下载。不,这不是语法错误。听着,我正在试图弄清楚为什么会出现这个错误,但是如果你不显示实际的代码,我就无能为力了;在这种方法中,您将生命周期/所有权转移到操作结果