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

Advice on Large Number of Routes


In our RouteConfig in an effort to have company profiles names as the some of our root URLs, we are adding a route for each company name, eg. xyz.com/acme

Whilst this appears to be working ok, I was hoping for some general advice on this, or a better way to solve it. I'm particularly concerned about performance, especially as we grow and we may have 10000+ companies and therefore 10000+ routes.

The code looks something like this:

foreach (string companyName in companyNameList)
{
    routes.MapRoute(
        name: companyName,
        url: companyName,
        defaults: new { controller = "CompanyProfile", action = "Index" });
}

Any advice would be greatly appreciated?


Solution

  • Can you not have a single route of the following form:

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

    Where CompanyConstraint is an IRouteConstraint that checks to ensure that the that the company name is valid? Something like this:

    internal class CompanyConstraint: IRouteConstraint
    {
        public CompanyConstaint(IList<string> companies)
        {
            this.companies = companies;
        }
    
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            object company;
            if (!values.TryGetValue("company", out company) || company == null)
            {
                 return false;
            }
    
            return companies.Contains(company.ToString());
        }
    }
    

    Cheers, Dean