Asp.net MVC 基于Area的路由映射

时间:2023-03-09 21:30:35
Asp.net  MVC  基于Area的路由映射

对于一个较大规模的Web应用,我们可以从功能上通过Area将其划分为较小的单元。每个Area相当于一个独立的子系统,具有一套包含Models、Views和Controller在内的目录结构和配置文件。一般来说,每个Area具有各自的路由规则(URL模版上一般会体现Area的名称),而基于Area的路由映射通过AreaRegistration进行注册。

一、创建Areas

  右键工程 -> 添加->区域

Asp.net  MVC  基于Area的路由映射

添加后生成一套包含Models、Views和Controller在内的目录结构和配置文件;只是多了一个 HomeAreaRegistration.cs文件

系统自动生成HomeAreaRegistration类 继承AreaRegistration

    public class HomeAreaRegistration : AreaRegistration
{ public override string AreaName
{
get
{
return "Home";
}
} public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Home_default",
"Home/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}

AreaRegistration:

  // 摘要:
// 提供在 ASP.NET MVC 应用程序内注册一个或多个区域的方式。
public abstract class AreaRegistration
{
// 摘要:
// 初始化 System.Web.Mvc.AreaRegistration 类的新实例。
protected AreaRegistration(); // 摘要:
// 获取要注册的区域的名称。
//
// 返回结果:
// 要注册的区域的名称。
public abstract string AreaName { get; } // 摘要:
// 注册 ASP.NET MVC 应用程序中的所有区域。
public static void RegisterAllAreas();
//
// 摘要:
// 使用指定的用户定义信息在 ASP.NET MVC 应用程序内注册所有区域。
//
// 参数:
// state:
// 一个包含要传递到区域中的用户定义信息的对象。
public static void RegisterAllAreas(object state);
//
// 摘要:
// 使用指定区域的上下文信息在 ASP.NET MVC 应用程序内注册某个区域。
//
// 参数:
// context:
// 对注册区域所需的信息进行封装。
public abstract void RegisterArea(AreaRegistrationContext context);
}

RegisterArea 方法不需要我们手动去调用,在 Global.asax 中的 Application_Start 方法已经有下面这样一句代码为我们做好了这件事:

 AreaRegistration.RegisterAllAreas();
 protected void Application_Start()
{
AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles); }

这时候如果你在 根目录的 Controller 文件 已经新建了一个HomeController  运行工程项目会报错,会提示已经存在Home

当Area被注册的时候,Area中定义的路由被限制了只寻找 Area 中的Controller。然而我们在RouteConfig.cs文件的RegisterRoutes方法中定义的路由并没有类似的限制

这时候在系统默认路由配置RouteConfig.cs文件中做修改

配置中添加 namespaces 指定命名空间

添加了 namespaces 参数后,路由系统在对这个路由进行匹配时,优先匹配指定命名空间的controller,如果匹配到则即刻停止查找,如果在指定的命名空间下没有匹配到对应的controller,再按照一般的方式进行匹配。

    public class RouteConfig
{ private static string[] namespaces = new string[] { "Bp.GMS.Web.Controllers" };
public static void RegisterRoutes(RouteCollection routes)
{ routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: namespaces
);
}
}