关于大量路线的建议

时间:2012-08-01 13:11:25

标签: c# .net asp.net-mvc-4 asp.net-routing

在我们的RouteConfig中,为了将公司简介名称作为我们的一些根URL,我们为每个公司名称添加了一条路线,例如。 xyz.com/acme

虽然这似乎工作正常,但我希望就此提出一些一般性建议,或者更好的解决方法。我特别关注绩效,特别是在我们成长的过程中,我们可能拥有10000多家公司,因此有10000多条路线。

代码看起来像这样:

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

任何建议都会受到高度赞赏?

1 个答案:

答案 0 :(得分:3)

你有没有以下形式的单一路线:

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

CompanyConstraintIRouteConstraint,检查以确保公司名称有效?像这样:

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());
    }
}

干杯, 迪安