How to have folder and controller with same name in ASP.NET MVC?

回眸只為那壹抹淺笑 提交于 2019-11-27 23:40:59

问题


I have a MVC controller called Downloads. http://mysite/Downloads

I also want to put a physical file in a physical folder called http://mysite/Downloads/MyFile.zip.

If I simply create a folder, I get a 403 when browsing to http://mysite/Downloads. (Most likely because of directory browsing is disabled) But I want the MVC controller to kick in instead.

How do I do that?


回答1:


If you browse to http://mysite/Downloads/{ACTION} it will fire your controllers action.

The only thing that won't work in your example is the /Downloads with no action. You could re-write this URL to redirect you to your default action.

In addition, you will need to have the routehandler ignore your download files. You can add a line in your global.asax file to ignore all zip files or some other ignore pattern that suits.

routes.Ignore("{resource}.zip");



回答2:


Since .NET 3.5, you can route existing files:

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

So suppose we had a folder on the site root called Markets containing an audio.mp3 file:

\Markets
\Markets\audio.mp3

Assuming the existence of a MarketsController, if we made a request for Markets, it'd be routed to Markets/Index.

If we requested /Markets/audio.mp3 we'd get the mp3 file and if we requested Markets/AnythingElse, normal routing would apply.



来源:https://stackoverflow.com/questions/1437386/how-to-have-folder-and-controller-with-same-name-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!