gpt4 book ai didi

c# - WebApi PushStreamContent 错误处理

转载 作者:行者123 更新时间:2023-11-30 12:57:36 26 4
gpt4 key购买 nike

使用 Pushstreamcontent 时处理错误的正确方法是什么?我使用 Pushstreamcontent 将数据直接从数据库流式传输到客户端。在客户端上,我在接收结果时使用 HttpCompletionOption.ResponseHeadersRead

在数据不可用的情况下,我想返回一个 HttpStatusCode 404(例如未找到)。目前我只检测到在执行 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;
}

最佳答案

您无法在 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;
}

关于c# - WebApi PushStreamContent 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33562099/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com