对于类别名称在电子商店MVC 2.0动态路由 [英] MVC 2.0 dynamic routing for category names in an e-store

查看:102
本文介绍了对于类别名称在电子商店MVC 2.0动态路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用ASP.NET MVC 2.0的电子商店。我已经得到了大部分运行起来,但是这一直困扰着我的部分是路由选择。我想这样的:

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

你觉得呢?这是一个好主意?我可能会拥有大约200类,是太多路线,以在路由表中有哪些?你会建议其他解决方案?

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?

感谢。

问候,
 安泽

Regards, Anže

推荐答案

与动态约束的单一路线可能是一个更好的解决方案。刚刚成立,只有符合您的类别的约束。

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

这篇关于对于类别名称在电子商店MVC 2.0动态路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆