【发布时间】:2011-08-04 05:44:43
【问题描述】:
是否可以在网站的各个部分定义路由。
例如,如果我想将网站的功能分解为模块,每个模块都会定义它需要的路由。
这可能吗?怎么样?
【问题讨论】:
标签: c# asp.net-mvc
是否可以在网站的各个部分定义路由。
例如,如果我想将网站的功能分解为模块,每个模块都会定义它需要的路由。
这可能吗?怎么样?
【问题讨论】:
标签: c# asp.net-mvc
考虑使用 ASP.NET MVC 的内置 Areas。
“区域”本质上是您的模块,区域允许您为每个特定区域注册路线。
如果您在此处有 MSDN 演练之前没有使用过它们:
http://msdn.microsoft.com/en-us/library/ee671793.aspx
基本上,每个区域都有一个目录,其中包含所有区域特定的控制器和视图,并且在该目录的路由中放置一个文件,该文件为该特定区域注册路由,如下所示:
public class MyAreaRegistration : AreaRegistration
{
public override string AreaName
{
get { return "My Area"; }
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"news-articles",
"my-area/articles/after/{date}",
new {controller = "MyAreaArticles", action = "After"}
);
// And so on ...
}
}
在 global.asax.cs 中,您需要注册所有这些额外区域以及其他主要路线:
public static void RegisterRoutes(RouteCollection routes)
{
AreaRegistration.RegisterAllAreas();
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Products",
"products/show/{name}",
new {controller = "Products", action = "Show", name = UrlParameter.Optional}
);
...
}
【讨论】:
您可以在每个模块中放置一个DefineRoutes(RouteCollection routes) 方法,然后在 Global.asax.cs 中调用它们。
【讨论】:
typeof(MyType).Assembly.GetTypes() 并找到所有实现IModuleInitializer 接口或类似接口的类型。