Search code examples
asp.net-mvcurl-routing

MVC custom URL routing


I have a route configured like

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

It works fine to redirect to respective controller and actions.

I want to add another redirection on TEST so that if somebody uses www.mysite.com/TEST, it should redirect www.mysite.com/Test/Home instead of giving 403- Forbidden: Access is denied error.

I'm trying like this but could not achieve it.

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

Basically, what I'm trying to do is to redirect from www.mysite.com or www.mysite.com/TEST to www.mysite.com/TEST/Home

To add to the confusion, I also had a physical folder TEST in my application root. Just wondering if keeping another web.config in there would solve? I tried but of no luck

Please advise what i'm missing here. Thanks

After some experiment I have found that the physical folder TEST is causing redirection rule to fail. I changed my route to TEST1 in URL instead of TEST, it worked. But, I can't rename TEST folder. Please advise


Solution

  • Please set the property RouteExistingFiles to true above the Route configurations

    public static void RegisterRoutes(RouteCollection routes)
        {
            routes.RouteExistingFiles = true;
    
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
            routes.MapRoute(
                name: "Default",
                url: "TEST/{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
    
        }
    

    This should allow you to keep the name of folder and also the route name to be "TEST". Let me know how it works out for you