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 Accounts
Azure Storage Accounts
Globally unique resources that provide access to data management services and serve as the parent namespace for the services.
3,223 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,614 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
343 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 66,706 Reputation points
    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.