MVC - ActionLink查找视图而不是调用控制器方法

时间:2016-09-26 06:53:40

标签: asp.net-mvc download actionlink fileresult

我想在我的网站上创建链接,点击后会打开下载窗口(只是一些简单的文本文件)。在几个教程中,我找到了一种方法,但是,出于某种原因,似乎ActionLink没有调用我的方法而是查找视图

我的ActionLink

@Html.ActionLink("here is the gpx log", "Download", "Treks")

我在Treks控制器中的下载方法(如果遇到乱七八糟的情况,还添加了使用属性路由的方法)

public FileResult Download()
{
    byte[] fileBytes = System.IO.File.ReadAllBytes(@"~/Files/file.txt");
    string fileName = "file.txt"; //I will add parameters later, once the basics work
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}


[Route("treks/{trekname}")] //Route: /Users/12
public ActionResult ShowTrek(string trekname) 
{
    return View(trekname);
}

这是我总是得到的错误

  

未找到“下载”视图或其主视图或视图引擎不支持搜索的位置。搜索了以下位置..

     

〜/ Views / Treks / DownloadFiles.aspx blahblahbla:

我花了一个小时研究这个问题,但仍然没有接近解决方案。有人知道我在哪里弄错了吗?非常感谢

更新:这是我的RouteConfig文件的内容

public static void RegisterRoutes(RouteCollection routes)
       {
       routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
       routes.MapMvcAttributeRoutes();

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

编辑:好的,我调试了它。似乎问题出在属性路由中。出于某种原因,控制器忽略了下载方法并直接进入ActionResult ShowTrek ...任何想法如何修复它?

2 个答案:

答案 0 :(得分:0)

尝试将Fileresult替换为FileStreamResult 您可能还需要在方法中创建文件流对象

new FileStream(fileName, FileMode.Open)

public FileStreamResult Download()
{
 // Your code

}

答案 1 :(得分:0)

解决。问题出在属性路由中。请在评论中查看Stephen Muecke的答案