将区域添加到 ASP.NET MVC 应用程序时,Visual Studio 将创建一个名为AreaRegistration的文件。 该文件包含从 AreaRegistration 派生的类。 此类定义了AreaName属性和RegisterArea方法,该方法将为新区域注册路由信息。
下面的示例显示了为名为Blog的新区域创建的AreaRegistration类。
public class BlogAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Blog";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Blog_default",
"Blog/{controller}/{action}/{id}",
new { action = "Index", id = "" }
);
}
}
Public Class BlogAreaRegistration
Inherits AreaRegistration
Public Overrides ReadOnly Property AreaName() As String
Get
Return "Blog"
End Get
End Property
Public Overrides Sub RegisterArea(ByVal context As System.Web.Mvc.AreaRegistrationContext)
context.MapRoute( _
"Blog_default", _
"Blog/{controller}/{action}/{id}", _
New With {.action = "Index", .id = ""} _
)
End Sub
End Class
Global.asax 文件包含在 ASP.NET MVC 应用程序启动时将调用的RegisterRoutes方法。 实现区域的任何应用程序的RegisterRoutes方法必须包含对 RegisterAllAreas 方法的调用。
下面的示例显示了包含对RegisterAllAreas的调用的RegisterRoutes方法。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
AreaRegistration.RegisterAllAreas();
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
[Visual Basic]
Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
AreaRegistration.RegisterAllAreas()
routes.MapRoute( _
"Default", _
"{controller}/{action}/{id}", _
New With {.controller = "Home", .action = "Index", .id = ""} _
)
End Sub