【问题标题】:How to have folder and controller with same name in ASP.NET MVC?如何在 ASP.NET MVC 中拥有同名的文件夹和控制器?
【发布时间】:2010-11-29 01:44:36
【问题描述】:
【问题讨论】:
标签:
.net
asp.net-mvc
asp.net-mvc-routing
【解决方案1】:
如果您浏览到http://mysite/Downloads/{ACTION},它将触发您的控制器操作。
在您的示例中唯一不起作用的是 /Downloads 没有任何操作。您可以重写此 URL 以将您重定向到您的默认操作。
此外,您需要让路由处理程序忽略您的下载文件。您可以在 global.asax 文件中添加一行以忽略所有 zip 文件或其他适合的忽略模式。
routes.Ignore("{resource}.zip");
【解决方案2】:
从 .NET 3.5 开始,您可以路由现有文件:
public static void RegisterRoutes(RouteCollection routes) {
routes.RouteExistingFiles = true;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home",
action = "Index",
id = UrlParameter.Optional }
);
}
假设我们在站点根目录中有一个名为 Markets 的文件夹,其中包含一个 audio.mp3 文件:
\Markets
\Markets\audio.mp3
假设存在MarketsController,如果我们请求Markets,它将被路由到Markets/Index。
如果我们请求 /Markets/audio.mp3,我们将获得 mp3 文件,如果我们请求 Markets/AnythingElse,则将应用正常路由。