當使用Pushstreamcontent時,處理錯誤的正確方法是什麼? 我使用Pushstreamcontent將數據直接從數據庫傳輸到客戶端。 在接收結果時,我在客戶端使用HttpCompletionOption.ResponseHeadersRead。WebApi 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;
}