【问题标题】:How to make a download file response in .net core?如何在.net核心中做出下载文件响应?
【发布时间】:2021-03-31 07:21:19
【问题描述】:

我正在使用endpoints.Map("/{*name}", RequestDelegate) 方法制作下载文件API。

RequestDelegate处理程序方法中,我使用await context.Response.SendFileAsync(IFileInfo)方法返回文件。

然后,我在浏览器中请求这个API,但是浏览器没有下载它,而是直接在浏览器中显示文件内容。我的代码中缺少什么。我希望浏览器下载文件。

await context.Response.SendFileAsync(GetFile(val));

private IFileInfo GetFile(string file_name)
{
    string downloadPath = Configuration.GetSection("DownloadFilePath").Get<string>();
    IFileProvider provider = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory);
    IFileInfo fileInfo = provider.GetFileInfo($"{downloadPath}/{file_name}");
    return fileInfo;
}

【问题讨论】:

    标签: c# asp.net-core asp.net-web-api


    【解决方案1】:

    有几件事情需要考虑:

    1. 浏览器现在检测文件并尝试像 PDF、Txt 文件一样自己处理它们,因为它们可以打开那些显示内容而不是下载的文件。
    2. 要进行下载,重要的是要确保发送正确的 HTML 标头,并使 Content-Disposition (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) 告诉并强制浏览器按照您的意愿行事。
    3. 如果您在文件中使用 HTML A 标签,您可以使用 download 属性来表示相同的内容。但我不确定它是否完全受支持。

    在您的代码中,我看到您没有发送任何类型的标头。最好设置缓存到期、处置、文件的内容类型(因为它是动态系统可能会发送默认内容类型,这可能会导致客户端工具混淆。)和内容长度。这些是发送的重要标头,以使您的代码正常工作。

    出于技术文档的目的,我不确定如何正确回答,但这些是我指导我的团队编写相同代码时的步骤。

    编辑:

    这些要点与编程语言无关,但取决于 Web 架构(HTTP 标准)。

    【讨论】:

    • 感谢您提供的详细信息。我已经弄清楚并在此处发布了答案。希望对其他初学者有所帮助。
    【解决方案2】:

    我想通了。我需要为其添加响应头。

    var fileinfo = GetFile(val);
    context.Response.Clear();
    context.Response.Headers.Add("Content-Disposition", "attachment;filename=" + fileinfo.Name);
    context.Response.Headers.Add("Content-Length", fileinfo.Length.ToString());
    context.Response.Headers.Add("Content-Transfer-Encoding", "binary");
    new FileExtensionContentTypeProvider().Mappings.TryGetValue(fileinfo.Extension, out var contenttype);
    context.Response.ContentType = contenttype ?? "application/octet-stream";
    await context.Response.SendFileAsync(fileinfo.FullName);
    
    private FileInfo GetFile(string file_name)
    {
        string downloadPath = Configuration.GetSection("DownloadFilePath").Get<string>();
        string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, downloadPath, file_name);
        FileInfo fileInfo = new FileInfo(path);
        return fileInfo;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-01
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多