文件下载asp.net mvc

kan*_*oid 3 model-view-controller asp.net-mvc download

我正在按照教程从服务器下载文件.但有点麻烦.我一定是在做一些愚蠢的错误.. !!

这是我关注的链接:http://haacked.com/archive/2008/05/10/writing-a-custom-file-download-action-result-for-asp.net-mvc.aspx

要求是; 用户将点击链接,该网站将把他们带到详细信息页面.在该详细信息页面上,将有一个下载链接.当用户点击该下载链接时,将下载该文件.

问题是,当我单击下载链接时,它不会下载原始文件.而是下载HTML文件.如果我单击HTML文件,它会显示垃圾.

这是我的代码:

行动:

public ActionResult Download(string path,string name)
    {
        return new DownloadResult { VirtualPath = path, FileDownloadName = name };
    }
Run Code Online (Sandbox Code Playgroud)

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 = this.VirtualPath; //context.HttpContext.Server.MapPath(this.VirtualPath);
        context.HttpContext.Response.TransmitFile(filePath);
    }
}
Run Code Online (Sandbox Code Playgroud)

与教程和我的代码的唯一区别是我使用的是实际的服务器路径.

任何的想法??

ale*_*exn 7

如果需要将文件发送到客户端并且您知道路径,请使用FilePathResult:

public ActionResult Download(string path, string name)
{
    return new FilePathResult(path, contentType) {
         FileDownloadName = name
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,您需要知道内容类型.如果您真的不知道,可以使用application/octet-stream哪个使浏览器将其视为二进制文件.