
我使用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;} 总结 以上是内存溢出为你收集整理的c# – WebApi PushStreamContent错误处理全部内容,希望文章能够帮你解决c# – WebApi PushStreamContent错误处理所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)