Search code examples
c#asp.net.netasp.net-mvcasp.net-mvc-routing

ASP.NET MVC routing URLs starting with numbers


Obviously in C# classes are not allowed to start with a number so how do I create controllers for URLs that start with a number in ASP.NET 4.6?

Example URL:

www.domain.com/40apples/

EDIT: Routing each URL individually will quickly become a pain to manage. Ideally, I'm looking for a solution that handles all number URLs. So that the above URL example routes to _40apples controller, 300cherries to _300cherries and 1orange to _1orange


Solution

  • You will have to use custom routing, in your RegisterRoutes method you could add another route that looks something like this:

    public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
            routes.MapRoute(
                "ApplesRoute",                                           // Route name
                "40apples/{action}",                            // URL with parameters
                new { controller = "Apples", action = "Index" }  // Parameter defaults
            );
    
            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );
        }
    

    If you would want your route to catch anything starting with a number + apples you could use a regex-constraint. Something like this:

    routes.MapRoute(
            "ApplesRoute",                                           // Route name
            "{number}apples/{action}",                            // URL with parameters
            new { controller = "Apples", action = "Index" }  // Parameter defaults
           ,new {number = @"\d+" } //constraint
        );
    

    An even more generic approach would be to catch all routes that starts with a number + a word. Then you could build your route and constraints something like this:

    routes.MapRoute(
            "NumbersRoute",                                           // Route name
            "{numberfruit}/{action}",                            // URL with parameters
            new { controller = "Numbers", action = "Index" }  // Parameter defaults
           ,new { numberfruit = @"\d+[A-Za-z]" } //constraint
        );
    

    EDIT after discussion with Organic:

    The approach that solved the problem in this case was using attribute routing. Which works well if you're using mvc 5 or greater.

    Then you would add an attribute route similar to this to your controller:

    [RoutePrefix("40apples")]
    

    And then another route to every specific action:

    [Route("{Buy}")]
    

    Do not forget to add routes.MapMvcAttributeRoutes(); to your route config.