使用.NET Core Razor页面将文件下载到浏览器 [英] Download file to browser using .NET Core Razor Pages
问题描述
我正在尝试使用ASP.NET Razor Pages将文件下载到浏览器.在Page(html)中,使用这样的链接可以正常工作:
Using ASP.NET Razor Pages, I am trying download a file to the browser. From the Page(html), using a link like this works fine:
href="/DownloadableFiles/testB.csv" download="newname">Download Link
但是,我想从代码隐藏或 ViewModel
开始下载,这样就可以动态了解文件名,我还需要先检查文件,等等.
However, I want to initiate the download from the code-behind or ViewModel
so it can be dynamic as to what the filename is, I also need to inspect the file first, etc.
在ASP.NET MVC核心(不是RazorPages)中,您可以使用以下代码下载文件:
In ASP.NET MVC core, (not RazorPages) you can download a file in code using:
return File(memory, GetContentType(path), Path.GetFileName(path));
但是Razor页面中不支持返回文件
.
But return File
is not supported in Razor Pages.
推荐答案
pitaridis是正确的,Razor Pages中存在 return File
,我必须缺少命名空间.这将从代码隐藏"中下载文件:
pitaridis is correct, return File
exists in Razor Pages, I must have been missing a namespace.
This will download a file from Code Behind:
在页面中,这是提交"按钮:
In the page, here's the submit button:
<button type="submit" asp-page-handler="DownloadFile" style="width:75px"
class="cancel"> Download </button>
在PageModel中(后面的代码):
In the PageModel (code behind):
public ActionResult OnPostDownloadFile()
{
return File("/DownloadableFiles/TestFile34.csv", "application/octet-stream",
"NewName34.csv");
}
注意:/DownloadableFiles位于wwwroot的子文件夹中
Note: /DownloadableFiles is in a subfolder of wwwroot
这篇关于使用.NET Core Razor页面将文件下载到浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!