WebApi Error Handling PushStreamContent

What is the correct way to handle errors when using Pushstreamcontent? I use Pushstreamcontent to stream data directly from the database to the client. On the client, I use HttpCompletionOption.ResponseHeadersRead when getting the result.

In case the data is not available, I want, for example, to return HttpStatusCode 404 (not found). Currently, I find that there is no data at runtime lambda (CopyBinaryValueToResponseStream). At this point, I can no longer change the state of the HttpResponeMessage.

So, how to deal with such cases? I wanted to avoid additional validation in the database, but right now it seems to be the only way to do this?

    [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;
    }
Run code
+4
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;
}
0

Source: https://habr.com/ru/post/1614693/