我是ASP.NET MVC的新手,我正面临一些结构设计问题 .
我无法弄清楚如何设置路由 .
我想要以下内容:
http://website/ > HomeController Action=Index
Public:
http://website/{controller} > SectionController Action=Index
http://website/products/id > ProductsController Action=Details
http://website/products/category/id > ProductsController Action=ListByCatId
http://website/products/categories/ > ProductsController Action=ListCategories
http://website/products/categories/id > ProductsController Action=DetailsCategories
Admin:
http://website/admin/ > AdminController Action=Index
http://website/admin/{controller} > SectionController Action=Index
对于大多数部件,默认的mapRoute都可以:
routes.MapRoute("Default", "{controller}/{action}/{id}", _
New With {.controller = "Home", .action = "Index", .id = ""})
当我开始把'category'而不是产品的id时,问题就开始了......
Should I 'hardcode' the routeUrls, e.g. "products/category/"?
对于管理员部分:
I'd like to put all controllers belonging to the Admin section of the website in: /Controllers/Admin/XxxController.vb. Is it possible to Namespace them and let them have the same name as in the public section? e.q. - Website.ProductsController class for public parts and - Website.Admin.ProductsController for the Admin section? How should I setup this?
2 回答
我就是这样做的:
至于具有两个具有相同名称的控制器,是的,您可以使用不同的命名空间并在mapRoute方法中指定它们 . 有一个重载需要
string[] namespaces
. 只需确保在路由时为控制器指定名称空间 .是的,如果您需要添加与默认值不对应的其他路由,请继续执行此操作 . 您将需要在默认路由上添加其他自定义路由,并在添加路由时使用从窄到宽的顺序(以便首先进行窄匹配) . 我建议让你的控制器动作尽可能地与你想要的默认命名相匹配 .
代替:
使用:
您的Index方法可以采用可为空的int(int?Id),其中Id对应于定义的产品 . 如果Id.HasValue为false,则返回ListCategories结果 .
这可以使您的附加路由更清洁 .