Download file to browser using .NET Core Razor Pages

若如初见. 提交于 2019-12-21 02:38:13

问题


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

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.

In ASP.NET MVC core, (not RazorPages) you can download a file in code using:

return File(memory, GetContentType(path), Path.GetFileName(path));

But return File is not supported in Razor Pages.


回答1:


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>

In the PageModel (code behind):

public ActionResult OnPostDownloadFile()
{
    return File("/DownloadableFiles/TestFile34.csv", "application/octet-stream", 
                "NewName34.csv");
}

Note: /DownloadableFiles is in a subfolder of wwwroot



来源:https://stackoverflow.com/questions/48952832/download-file-to-browser-using-net-core-razor-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!