【问题标题】:WebApi PushStreamContent Error HandlingWebApi PushStreamContent 错误处理
【发布时间】:2016-02-07 07:45:13
【问题描述】:

使用 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;
    }

【问题讨论】:

    标签: c# asp.net-web-api pushstreamcontent


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-04-16
      • 1970-01-01
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多