MVC 4.5 URL.Action 和路由

MVC 4.5 URL.Action and routes

我首先制作了一个 UrlHelperExtension class 构建了我的 url 喜欢这个

"/Home/DownloadFiles?directory="+directory+"&filename"+HttpUtility.UrlEncode(filename)

但我想为什么不使用 mvc 来构建我的 URL,所以在我看来我做到了

href="@Url.Action("DownloadFiles","Home", new {directory = "files", filename="1.mp3"}"

但是输出 /Home/DownloadFiles/files/1.mp3 找不到文件(我收到 404)。我的操作方法是

public ActionResult DownloadFiles(string directory, string filename){
  //log which file is downloaded by who
  //Add download header content-disposition attachement
  //Send response with the file
  return null;
}

我唯一的路线是这样的

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

我想我在真正理解路线时遇到了一些问题,因为我不确定如何解决这个问题,所以我不必使用我的扩展程序 class,它实际上并没有太大作用。也许我不应该使用 URL.Action ? Url.Action UrlEncode 文件名参数吗?目录参数只有 1 "deep" 所以它不能 abc/def 只有 abc 并且我添加到它相关的部分所以我不担心 UrlEncoding 它。

你得到一个 404,不是因为你的路由有问题(它们看起来很好),而是因为路径 /Home/DownloadFiles/files/282.mp3 被作为静态文件处理,这当然不存在.

尝试将以下内容添加到您的 web.config

<configuration>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true" />
    </system.webServer>
</configuration>

更新

如果性能是个问题。改为将此添加到您的 web.config

<system.webServer>
  <handlers>
    <add name="Mp3FileHandler" path="*.mp3" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
</system.webServer>