使用Pushstreamcontent时处理错误的正确方法是什么?
我使用Pushstreamcontent将数据直接从数据库传输到客户端.
在客户端上,我在收到结果时使用HttpCompletionoption.ResponseHeadersRead.
我使用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; }
解决方法
您无法在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,context) => { // can't do anything here,already sent a 200. await copyBinaryValuetoResponseStream(responseStream,id); }); return resp; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。