Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC route where path exists

I'm trying to create a route that will caption a url like

http://mysite.com/tech/

but I also have an actual directory under the site that is /tech, which contains other static resources. Not my design choice, but I'm migrating an older site to mvc and dont want to break a bunch of very old links.

My route seems to keep failing, and what I can figure is that the server sees this directory and is trying to serve up the default file from it... but none is found, and it fails.

I'd like it to use my route instead and let me serve up my view. Any best practices for this?

UPDATE: I tried using RouteExistingFiles = true, which made this work, but then I had issues with files which existed inside these directories. (for instance: http://mysite.com/tech/image.jpg). I started adding IgnoreRoute entries for all the various file types that I wanted ignored (ie .jpg files..), but this turned into a big mess. There's gotta be a better way?

like image 275
Brady Moritz Avatar asked Aug 27 '11 19:08

Brady Moritz


1 Answers

You need to set the RouteExistingFiles property of your RouteCollections object to true. This will make your routing override the physical location if a clash is found.

routes.MapRoute("Default", "{controller}/{action}/{id}",
        new { controller = "Home", action = "Index", id = "" }
    );
routes.RouteExistingFiles = true;

To selectively ignore files/extensions you can use :

routes.IgnoreRoute("{*staticfile}", new { staticfile = @".*\.(css|js|gif|jpg)(/.*)?" });

Another approach which might help if you don't like the ignoreRoute approach, is to extend the ViewEngine and override the file exists implementaion with your own rules.

public class MyViewEngine : RazorViewEngine
{
    protected override bool FileExists(ControllerContext controllerContext, string virtualPath)
    {
        //Some Logic to check for file
    }
}

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new CustomViewEngine());
like image 73
TheCodeKing Avatar answered Oct 02 '22 22:10

TheCodeKing