I have the following action that is generating a file:
public async Task<IActionResult> GetFile()
{
//some long running action to actually generate the content
//(e.g. getting data from DB for reporting)
await Task.Delay(10000);
return File(new byte[]{}, "application/octet-stream");
}
The problem is that when user follows that link, there's a long delay between hitting an action and the browser displaying the file as being downloaded.
What I actually want, is for ASP.Net to send headers with filename (so the browser would show to the user that file has started to download) and delay sending the Body while file contents is generated. Is it possible to do this?
I tried the following:
public async Task GetFile()
{
HttpResponse response = this.HttpContext.Response;
response.ContentType = "application/octet-stream";
response.Headers["Content-Disposition"] = "inline; filename=\"Report.txt\"";
//without writing the first 8 bytes
//Chrome doesn't display the file as being downloaded
//(or ASP.Net doesn't actually send the headers).
//The problem is, I don't know the first 8 bytes of the file :)
await response.WriteAsync(string.Concat(Enumerable.Repeat("1", 8)));
await response.Body.FlushAsync();
await Task.Delay(10000);
await response.WriteAsync("1234567890");
}
The code above works, and I'd be happy with it, if I didn't have to response.WriteAsync
first 8 bytes for headers to be sent.
Are there other ways to overcome it?