MVC 2.0 dynamic routing for category names in an e-store

坚强是说给别人听的谎言 提交于 2020-01-12 07:56:06

问题


I'm currently working on an e-store using ASP.NET MVC 2.0. I already got most of it up and running, but the part that's been bothering me is routing. I want this:

http://mystore.somewhere/my-category-1/

So far I've been able to solve it by using:

routes.MapRoute(
            "Category",
            "{alias}/{pageNumber}",
            new { controller = "Categories", action = "Browse", pageNumber = 1 });

But this catches way too much than just what I'd like.

After reading through some questions and answers around this site, I found a particulary interesting solution that would require me to programatically register a route for each of my categories, so in essence I'd be doing

 foreach (var c in Categories)
        {
            routes.MapRoute(
                c.Name,
                "{" + c.Alias + "}/{action}/...anything else",
                new { controller = "Category", action = "Index" }).RouteHandler = new CateegoryRouteHandler(c);
        }

What do you think? Is this a good idea? I'm probably going to have about 200 categories, is that too much "routes" to have in the routing table? Would you suggest another solution?

Thanks.

Regards, Anže


回答1:


A single route with a dynamic constraint might be a more elegant solution. Just set up a constraint that only matches your categories.

     routes.MapRoute(
        "Category",
        "{alias}/{pageNumber}",
        new { controller = "Categories", action = "Browse", alias = UrlParameter.Optional, pageNumber = 1 },
        new { alias = new CategoryMatchConstraint() } );


 public class CategoryMatchConstraint : IRouteConstraint
 {
      public bool Match( HttpContextBase httpContext,
                         Route route,
                         string parameterName,
                         RouteValueDictionary values,
                         RouteDirection routeDirection )
      {
           var category = values.Values[parameterName] as string;
           if (string.IsNullOrEmpty(category))
           {
                return false;
           }
           using (var db = new MyDatabaseContext())
           {
                return db.Categories.Any( c => c.Name == category );
           }
      }
}


来源:https://stackoverflow.com/questions/3325140/mvc-2-0-dynamic-routing-for-category-names-in-an-e-store

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!