Bob*_*eck 4 c# asp.net razor-pages
我正在尝试使用ASP.NET Razor Pages将文件下载到浏览器。从Page(html),使用这样的链接可以正常工作:
href="/DownloadableFiles/testB.csv" download="newname">Download Link
Run Code Online (Sandbox Code Playgroud)
但是,我想从后面的代码启动下载,ViewModel这样就可以动态了解文件名,我还需要先检查文件,依此类推。
在ASP.NET MVC核心(不是RazorPages)中,可以使用以下代码下载文件:
return File(memory, GetContentType(path), Path.GetFileName(path));
Run Code Online (Sandbox Code Playgroud)
但是return FileRazor Pages不支持。
It's also possible to use a GET call instead of POST like this:
Put this in your page code behind:
public ActionResult OnGetDownload()
{
return File("c:/Directory/FileName.csv", "application/octet-stream", "FileName.csv");
}
Run Code Online (Sandbox Code Playgroud)
And put this on that page:
<a href="@Url.Page("ThePageName", "Download")>Download</a>
Run Code Online (Sandbox Code Playgroud)
If you want to pass parameters, just include them in the Url.Page call and add parameters to OnGetDownload like this:
public ActionResult OnGetDownload(int Id)
{
return File("c:/Directory/FileName.csv", "application/octet-stream", "FileName.csv");
}
<a href="@Url.Page("ThePageName", "Download", new { Model.Id })">Download</a>
Run Code Online (Sandbox Code Playgroud)
pitaridis是正确的,return File存在于Razor Pages中,我必须缺少名称空间。这将从“代码隐藏”中下载文件:
在页面中,这是“提交”按钮:
<button type="submit" asp-page-handler="DownloadFile" style="width:75px"
class="cancel"> Download </button>
Run Code Online (Sandbox Code Playgroud)
在PageModel(后面的代码)中:
<button type="submit" asp-page-handler="DownloadFile" style="width:75px"
class="cancel"> Download </button>
Run Code Online (Sandbox Code Playgroud)
注意:/ DownloadableFiles在wwwroot的子文件夹中