简体   繁体   English

从ASP.net MVC中的服务器下载文件(找不到错误404)

[英]Downloading file from server in ASP.net MVC (Error 404 not found)

I have a simple Action which should allow me to download an asked file. 我有一个简单的操作,该操作应允许我下载要求的文件。

This works perfectly if I call the action using the browser's context menu (see the screenshot below), but when I click the link directly I get the following error: HTTP Error 404.0 - Not Found - The resource you are looking for has been removed, had its name changed, or is temporarily unavailable. 如果我使用浏览器的上下文菜单调用该操作,则效果很好(请参见下面的屏幕截图),但是当我直接单击链接时,出现以下错误: HTTP错误404.0-找不到-您正在寻找的资源已被删除,更名,或暂时不可用。

Using browser's context menu: 使用浏览器的上下文菜单:

在此处输入图片说明

Controller Action for downloading files: 用于下载文件的控制器操作:

public ActionResult Download(string id)
{
    string username = User.Identity.Name;
    Client client = db.Client.SingleOrDefault(x => x.Email == username);

    string filePath = Server.MapPath("~/Client-Documents/" + client.FolderName + "/" + id);

    return File(filePath, "text/plain", id);
}

View snippet where the file links are being generated: 查看正在生成文件链接的代码段:

@for (int i = 0; i < Model.Count(); i++)
{
    <tr>
        <td>@(i + 1)</td>
        <td>@Model[i].Name</td>
        <td>
            <a href="@Url.Action("Download", "Client", new { @area = "Administration", id = Model[i].Location })">Download</a>
        </td>
    </tr>
}

You were passing the filename which included the extension, so it was being ignored by ASP.NET and treated as a static file, thus resulting in a 404. To avoid this, don't pass the extension. 您正在传递包含扩展名的文件名,因此ASP.NET将忽略它并将其视为静态文件,从而产生404。为避免这种情况,请不要传递扩展名。 Probably best to refer to the files by ID. 可能最好按ID引用文件。

Also note that if the files are part of your data, it's probably best to store them in a database. 还要注意,如果文件是数据的一部分,则最好将它们存储在数据库中。 This avoids many file system pitfalls. 这避免了许多文件系统陷阱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM