简体   繁体   中英

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.

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. Probably best to refer to the files by 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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