Send Chunked Response in .NET 6 Web Api

net 6 newbie 121 Reputation points
2024-01-27T18:09:38.9866667+00:00

I am building a Web API project where I will be fetching pdf files from Azure blob Storage and send the pdf files as response to API calls. I have tried using following piece of code

  Response.ContentType = "application/pdf"; 
await foreach (var block in azureStorage.DownloadBlobAsync(blobname, cancellationToken)) 
{
    
        await Response.Body.WriteAsync(block, 0, block.Length);
        await Response.Body.FlushAsync(); 
}
  return new EmptyResult();

Where

DownloadBlobAsync(blobname, cancellationToken)

method fetches pdf from from blobstorage in chunks of 4 MB and yield the Block. I am expected the pdf file to start rendering when it starts receiving the first chunk. But When I am running the above logic pdf file is rendering only after complete download. How to achieve rendering when it starts receiving the first chunk? I have read some blogs which red flags usage of

Response.Body.FlushAsync().

In .NET 6 Web API what are the different ways to send chunked response especially when return type is a file.

Azure Storage
Azure Storage
Globally unique resources that provide access to data management services and serve as the parent namespace for the services.
3,529 questions
Developer technologies ASP.NET ASP.NET Core
Developer technologies ASP.NET ASP.NET API
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2024-01-27T21:39:32.0533333+00:00

    How are you displaying the pdf? If it’s the browser default, you are out of luck. To display a pdf, after download, the browser calls the registered pdf viewer with the url. The file is fetched from the cache. This is prevent double fetch.

    you can get more control if you use pdf.js, a JavaScript pdf viewer used by chrome.

    and finally the format of the pdf effects display. Sometimes, data required to display the first page is at the end of the file. Remember a pdf file is a postscript program, not a data file.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.