简体   繁体   English

MVC 4.5 URL。动作和路由

[英]MVC 4.5 URL.Action and routes

I started by making an UrlHelperExtension class that built my url likes this 我首先制作了一个UrlHelperExtension类,该类构建了这样的网址

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

But i figure why not use mvc to build my URLs so in my view i did 但是我想为什么不使用mvc来构建我的URL,所以我认为

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

but that's outputting /Home/DownloadFiles/files/1.mp3 which can't find the file (i get a 404). 但这输出的/Home/DownloadFiles/files/1.mp3找不到文件(我得到404)。 my action method is 我的动作方法是

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;
}

and my only route looks like this 我唯一的路线是这样的

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

I think i have some issues really understanding routes because i'm not sure how to fix this so i dont have to use my extension class which really doesn't do much. 我认为我在真正理解路由时遇到了一些问题,因为我不确定如何解决此问题,因此我不必使用扩展类,而扩展类实际上并没有太大作用。 Maybe i shouldn't use URL.Action ? 也许我不应该使用URL.Action吗? Would Url.Action UrlEncode the filename parameter ? Url.Action UrlEncode将filename参数编码吗? the directory parameter is only 1 "deep" so it can't be abc/def only abc and i add to it relevant part so im not worried about UrlEncoding it. 目录参数只有1个“ deep”,因此它不能仅是abc / def,而我将其添加到相关部分,因此我不担心UrlEncoding。

You're getting a 404, not because you have an issue with your routes (they look fine), but because the path /Home/DownloadFiles/files/282.mp3 is being processed as a static file, which of course does not exist. 您得到的是404,不是因为您的路由存在问题(看起来不错),而是因为/Home/DownloadFiles/files/282.mp3路径正在作为静态文件处理,因此当然不存在。

Try adding the following to your web.config 尝试将以下内容添加到您的web.config

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

Update 更新资料

If performance is an issue. 如果性能是一个问题。 Add this to your web.config instead: 而是将其添加到您的web.config

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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