如何链接到ASP.NET MVC中的可下载文件?

Gau*_*ain 4 .net c# asp.net asp.net-mvc

我是ASP.NET MVC的新手,我试图链接到可下载的文件(.zip,.mp3,.doc等).
我有以下视图:ProductName 映射到:http://domain/ProductName
我有一个.zip必须映射到URL 的文件http://domain/ProductName/Product.zip

问题

我在哪里将此.zip文件放在MVC文件夹结构中?
如何.zip在MVC中添加此文件的链接?是否有这样做的Url.*方法?

小智 18

您可以使用FilePathResult或Controller.File方法.

protected internal virtual FilePathResult File(string fileName, string contentType, string fileDownloadName) {
  return new FilePathResult(fileName, contentType) { FileDownloadName = fileDownloadName };
}
Run Code Online (Sandbox Code Playgroud)

示例代码操作方法.

public ActionResult Download(){
  return File(fileName,contentType,downloadFileName);
}
Run Code Online (Sandbox Code Playgroud)

希望这段代码.


Rob*_*vey 8

以下类将一个文件添加DownloadResult到您的程序:

public class DownloadResult : ActionResult
{

    public DownloadResult()
    {
    }

    public DownloadResult(string virtualPath)
    {
        this.VirtualPath = virtualPath;
    }

    public string VirtualPath { get; set; }

    public string FileDownloadName { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        if (!String.IsNullOrEmpty(FileDownloadName))
        {
            context.HttpContext.Response.AddHeader("content-disposition",
              "attachment; filename=" + this.FileDownloadName);
        }

        string filePath = context.HttpContext.Server.MapPath(this.VirtualPath);
        context.HttpContext.Response.TransmitFile(filePath);
    }
}
Run Code Online (Sandbox Code Playgroud)

要调用它,在控制器方法中执行以下操作:

public ActionResult Download(string name)
{
    return new DownloadResult 
       { VirtualPath = "~/files/" + name, FileDownloadName = name };
}
Run Code Online (Sandbox Code Playgroud)

注意虚拟路径,它是站点根目录中的文件目录; 这可以更改为您想要的任何文件夹.这是您放置文件以供下载的地方.查看本教程,了解如何为ASP.NET MVC编写自定义文件下载操作结果