2015-11-06 71 views
4

當使用Pushstreamcontent時,處理錯誤的正確方法是什麼? 我使用Pushstreamcontent將數據直接從數據庫傳輸到客戶端。 在接收結果時,我在客戶端使用HttpCompletionOption.ResponseHeadersReadWebApi PushStreamContent錯誤處理

在數據不可用的情況下,我想返回一個HttpStatusCode 404(Not Found)例如。 目前我只檢測到在執行lambda期間沒有數據(CopyBinaryValueToResponseStream)。 在那個時候,我無法再改變HttpResponeMessage的狀態。

那麼處理這種情況的正確方法是什麼?我想避免在數據庫中進行額外的檢查,但是現在似乎是完成它的唯一方法?

[Route("{id}")] 
 
    public HttpResponseMessage GetImage(int id) 
 
    { 
 
     HttpResponseMessage resp = new HttpResponseMessage(); 
 

 
     // do I need to check here first if the data is available? 
 
     // and return 404 if the data is not available 
 
     // resp.StatusCode = HttpStatusCode.NotFound 
 
     // or can I handle it later from within the lambda? 
 

 
     resp.Content = new PushStreamContent(async (responseStream, content, context) => 
 
     { 
 
      // what if an error happens in this function? who do I get that error to the client? 
 
      await CopyBinaryValueToResponseStream(responseStream, id); 
 
     }); 
 

 
     return resp; 
 
    }

回答

0

不能在PushStreamContent行動中修復它。當動作執行的時候,你已經開始發送響應了,因此已經發送了200.這是PushStreamContent的一個缺點。

如果您有一些方法可以在流式傳輸之前檢測到資源不存在(例如,如果某個文件不存在),那麼您可以首先檢測到並返回404,即在此情況下根本不使用PushStreamContent 。

[Route("{id}")] 
public HttpResponseMessage GetImage(int id) 
{ 
    HttpResponseMessage resp = new HttpResponseMessage(); 

    if (File.Exists(@"c:\files\myfile.file")) 
    { 
     resp.StatusCode = HttpStatusCode.NotFound; 
     return resp; 
    } 

    // file exists - try to stream it 
    resp.Content = new PushStreamContent(async (responseStream, content, context) => 
    { 
     // can't do anything here, already sent a 200. 
     await CopyBinaryValueToResponseStream(responseStream, id); 
    }); 

    return resp; 
}