使用Pushstreamcontent时处理错误的正确方法是什么?我使用Pushstreamcontent将数据直接从数据库流式传输到客户端。在客户端上,我在接收结果时使用HttpCompletionOption.ResponseHeadersRead。
在数据不可用的情况下,我想返回一个 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;
}