使用MVC Core下载文件

Vag*_*gue 20 asp.net-core-mvc

我找不到使用MVC Core下载文件的参考.

我们有一个exe文件供会员从我们的网站下载.过去我们已经把

<a href=(file path)> Download < /a>供我们的用户点击.我想在MVC Core中做同样的事情

<a href=@ViewData["DownloadLink"]> Download < /a>
Run Code Online (Sandbox Code Playgroud)

使用下载链接填充文件路径.

public class DownloadController : Controller
{
    [HttpGet]
    public IActionResult Index()
    {
        ViewData["DownloadLink"] = ($"~/Downloads/{V9.Version}.exe");
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

`

链接<a href=@ViewData["DownloadLink"]> Download < /a>获取正确的路径,但单击时仅在地址栏中呈现路径.有没有简单的方法来设置下载链接?

Vag*_*gue 40

我使用@Tieson T发布的这个答案来提出这个解决方案

    public FileResult Download()
    {
        var fileName = $"{V9.Version}.exe";
        var filepath = $"Downloads/{fileName}";
        byte[] fileBytes = System.IO.File.ReadAllBytes(filepath);
        return File(fileBytes, "application/x-msdownload", fileName);
    }
Run Code Online (Sandbox Code Playgroud)

现在是观点

<a asp-action="Download" asp->
Download
Run Code Online (Sandbox Code Playgroud)

@Ageonix对于不要求〜来到wwwroot也是正确的