2017-03-25 98 views
-1

創建流對象,我有一個方法來下載文件S3C#使用語句

方法

Public ActionResult download(string filename, string credentials) 
{ 
    .... 
    Using(stream res = response from s3) 
    { 
     return file(res, type, filename); 
    } 
} 

但例外是扔在執行上述方法。

異常消息 - 請求被中止:連接被意外

關閉我有下載後釋放該流「RES」對象。

+0

什麼是'從s3'迴應? – DavidG

+0

大小爲50 MB的Zip文件 – anand

+0

不,不,確切的方法/函數/對象/數據類型/什麼? – DavidG

回答

1

File方法返回一個ActionResult的情況下,你是轉移責任流關閉的動作,結果,所以你的確想打電話Dispose或使用using。這是爲了使ActionResult不需要緩衝數據。所以:剛取出using

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 
    } 
} 
+0

'文件'方法關閉流'res'對象,當它不再需要時 – anand

+0

是;在這種方法中,您將生命週期/所有權轉移到行動結果 –