Dan*_*elG 5 c# asp.net-web-api pushstreamcontent
使用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;
}Run Code Online (Sandbox Code Playgroud)
您无法在 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;
}
Run Code Online (Sandbox Code Playgroud)