c# – WebApi PushStreamContent错误处理
发布时间:2020-12-15 20:56:35 所属栏目:百科 来源:网络整理
导读:使用Pushstreamcontent时处理错误的正确方法是什么? 我使用Pushstreamcontent将数据直接从数据库传输到客户端. 在客户端上,我在收到结果时使用HttpCompletionOption.ResponseHeadersRead. 在数据不可用的情况下,我想返回例如HttpStatusCode 404(Not Found).
使用Pushstreamcontent时处理错误的正确方法是什么?
我使用Pushstreamcontent将数据直接从数据库传输到客户端. 在客户端上,我在收到结果时使用HttpCompletionOption.ResponseHeadersRead. 在数据不可用的情况下,我想返回例如HttpStatusCode 404(Not Found). 那么处理此类案件的正确方法是什么?我想提前避免在数据库中进行额外的检查,但是现在这似乎是完成它的唯一方法吗? [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:filesmyfile.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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |