Legends
Legends

Reputation: 22722

The resource cannot be found ( controller action MVC 5, .NET 4.6.1)

I am trying to download a file, when I click on a hyperlink, but I always get a Resource not found exception.

The controller action never gets hit.

Index.cs.html:

@{
    ViewBag.Title = "Files";
}

@Html.ActionLink("Download Report", "DownloadFile", "FileDownload", new { type = "pdf" }, new { @class = "" })

Rendered Action-Link: http://localhost:58255/FileDownload/DownloadFile?type=pdf

Without Files route

When I uncomment the MapRoute entry "Files" in the routeConfig the action link is rendered like this: http://localhost:58255/FileDownload/DownloadFile/pdf

With Files route defined

But neither of them work! -> The resource cannot be found

Controller (Only Index action gets hit when the view loads, but nothing when I click on the actionlink):

[AllowAnonymous]
public class FileDownloadController : Controller
{

    public ActionResult Index()
    {
        return View();
    }

FilePathResult DownloadFile(string type)
{
   var fn = $"~/Documents/Test.{type}";
   return File(fn, "application/pdf", Server.UrlEncode(fn));
}

RegisterRoutes.cs:

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes(); // for attribute routing on action
AreaRegistration.RegisterAllAreas();

//routes.MapRoute(
//    name: "Files",
//    url: "{controller}/{action}/{type}",
//    defaults: new { controller = "FileDownload", action = "DownloadFile", type = UrlParameter.Optional }
//);

// Should be last
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}

...coming from the WebForms area...

Upvotes: 0

Views: 891

Answers (1)

Ashish Shukla
Ashish Shukla

Reputation: 1294

Please try to add public access modifier before action name

public FilePathResult DownloadFile(string type)
{
  var fn = $"~/Documents/Test.{type}";
  return File(fn, "application/pdf", Server.UrlEncode(fn));
}

Upvotes: 1

Related Questions