.NET MVC - Controller/View and physical path?

2019-08-21 23:29发布

问题:

Is it possible to have controller/view for URL:

http://mydomain/SomeFolder/

And a similar physical folder to put files in it

http://mydomain/SomeFolder/*.*

Currently URL http://mydomain/SomeFolder/, only returns the physical folder is browsed if web.config allows it, but I would like it to return the view and http://mydomain/SomeFolder/*.* to return the files contained in the folder.

回答1:

Yes, this is possible. Let's suppose that you have the ~/SomeFolder/foo.png file and a ~/Controllers/SomeFolderController. All you need to do is to set the RouteExistingFiles property to true:

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

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

    routes.RouteExistingFiles = true;
}

Now when you navigate to /SomeFolder or /SomeFolder/Index the Index action of the SomeFolder controller will be rendered. And when you navigate to /SomeFolder/foo.png the static file will be served.



回答2:

Here's the solution I found, I whish I had found some simpler way though.

With this solution I still cannot put files in the physical path of http://mydomain/SomeFolder/, this folder cannot exist physically otherwise the controller/view doesn't work. But what it will achieve is that http://mydomain/SomeFolder/SomeFile.zip returns the same file as http://mydomain/**Content**/SomeFolder/SomeFile.zip, which was my main goal.

I need to have two distinct routes for http://mydomain/SomeFolder/ and http://mydomain/SomeFolder/anything/file/etc

        routes.MapRoute(
            "SomeFolder",
            "SomeFolder",
            new { controller = "SomeFolder", action = "Index" }
        );

        routes.MapRoute(
            "SomeFolderSub",
            "SomeFolder/{*any}",
            new { controller = "TryDownloadFile", action = "Index" }
        );

routes.RouteExistingFiles remains false.

Then I have SomeFolderController that return SomeFolder's view. And TryDownloadFileController that checks if the file exists in http://mydomain/Content/SomeFolder/ instead of http://mydomain/SomeFolder/ and returns it.

(I guess if the file doesn't exist it should return some 404 response. Which would be return this.HttpNotFound();)