如何使用asp.net Core下载文件?

4
这是我在StackOverflow上的第一个问题。 经过多次研究,我没有找到一种方法可以在用户访问正确的URL时下载文件。
使用.Net Framework时,使用以下代码:
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
    response.ClearContent();
    response.Clear();
    response.ContentType = "text/plain";
    response.AddHeader("Content-Disposition", 
                       "attachment; filename=" + fileName + ";");
    response.TransmitFile(Server.MapPath("FileDownload.csv"));
    response.Flush();    
    response.End();

在 .Net Core 中有什么相当的东西吗? 谢谢


你是在询问用户如何从你的应用程序接收CSV文件,还是上传CSV文件到你的服务器? - Franco Pettigrosso
1个回答

12
如果您已经有一个控制器,请添加一个操作,返回磁盘上文件的PhysicalFile或内存中二进制文件的File
[HttpGet]
public ActionResult Download(string fileName) {
    var path = @"c:\FileDownload.csv";
    return PhysicalFile(path, "text/plain", fileName);
}
从项目文件夹注入IHostingEnvironment,并获取WebRootPath(wwroot文件夹)或ContentRootPath(根项目文件夹)的文件路径。
    var fileName = "FileDownload.csv";
    string contentRootPath = _hostingEnvironment.ContentRootPath;
    return PhysicalFile(Path.Combine(contentRootPath, fileName), "text/plain", fileName);

我正在使用 Razor Pages,因此没有控制器。 - Boursomaster
想法仍然相同,几乎没有区别,只需遵循 Razor Pages 约定 - 方法上没有属性,使用处理程序调用方法,例如 'OnGetFileDownload'。仍然可以传递参数,并且可以访问辅助方法 PhysicalFile - Ivvan
你的代码中的"text/plain"是什么意思?抱歉,我正在尝试理解它。 - DialFrost
1
@DialFrost 这里是一个媒体类型,它将在Content-Type头部返回给客户端,以便客户端可以正确解释结果。在这种情况下,浏览器将显示整个文件内容,作为纯文本而没有任何样式和脚本。 - Ivvan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接