Asp.Net 核心:如何让浏览器在发送文件之前显示正在下载

Asp.Net Core: how to make the browser show file as being downloaded before it's sent

我有以下生成文件的操作:

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");
}

问题在于,当用户关注 link 时,点击操作与浏览器显示正在下载的文件之间存在很长的延迟。

我真正想要的是 ASP.Net 发送 headers 和文件名(这样浏览器会向用户显示文件已经开始下载)并延迟发送 Body 同时生成文件内容。可以这样做吗?

我尝试了以下方法:

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");
}

上面的代码有效,如果我不必 response.WriteAsync 发送 headers 的前 8 个字节,我会很高兴。

还有其他方法可以克服吗?

实际上,有问题的代码可以正常工作。 问题是,Chrome doesn't show file as being downloaded until 8 bytes are sent

但是,如果您想编写类似的内容,请考虑阅读Stephen Cleary's post一些有用的抽象内容。