MVC 2.0动态路由,用于电子商店中的类别名称

Anž*_*nik 6 url-routing c#-4.0 asp.net-mvc-2

我目前正在使用ASP.NET MVC 2.0开发电子商店.我已经完成了大部分工作,但是一直困扰着我的部分是路由.我要这个:

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

到目前为止,我已经能够使用以下方法解决它:

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

但是,这比我想要的要多得多.

在阅读了本网站的一些问题和答案之后,我发现了一个特别有趣的解决方案,需要我以编程方式为每个类别注册一条路线,所以本质上我会做的

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

你怎么看?这是一个好主意吗?我可能会有大约200个类别,是否在路由表中有太多"路由"?你会建议另一个解决方案?

谢谢.

此致,Anže

tva*_*son 5

具有动态约束的单个路由可能是更优雅的解决方案.只需设置一个仅与您的类别匹配的约束.

     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 );
           }
      }
}
Run Code Online (Sandbox Code Playgroud)