简体   繁体   中英

ActionLink throws HTTP 404.0 – Not Found error // ASP.NET MVC

I've got an issue with passing name of clicked ActionLink to controller and using it. 404 error appears when click. This is part of my view called Scan.cshtml

<tbody >
                @foreach (string item in ViewBag.files)
                {
                    <tr>
                        <td class=" row col-md-12 "> @Html.ActionLink(item, "Download", "Scan", new { id = item }, new { style = "color: #424242" })</td>
                    </tr>
                }
            </tbody>

This is the part from ScanController where am I trying to operate with sent data. I think it doesn't get to the controller logic at all and throws error sooner.

    public ActionResult Download(string id)
    {
        // controller logic for downloading file
        var ftpko = new MyProject.Helpers.ftp(@path, name, passwd);
        ftpko.download(id, "~/Dotazniky/dotaznik.jpg"); 

        return View();
    }

Let's say item = "car.jpg", error says requested path - http://localhost:53593/Scan/Download/car.jpg not found.

This is the RouteConfig file:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

The problem is that you ending your url name with .jpg , and the request is going to search for a Content file, not to execute an Action.

There are ways to disable this, but i think the most easy solution is to send name and extension in separate parameters.

Action become:

public ActionResult Download(string name, string ext)
{ 
     string id = name + "." + ext;

Add a new route

routes.MapRoute(
        name: "TwoParameters",
        url: "{controller}/{action}/{name}/{ext}",
        defaults: new { controller = "Home", action = "Index"}
    );

Modify the ActionLink

@{ var params = item.Split('.'); }
@Html.ActionLink(item, "Download", "Scan", new { name = params[0], ext = params[1] }, new { style = "color: #424242" })

Notes: There are other ways (others than .Split('.') ) to take extension and the filename.

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