項目需區分 PC 和 Mobile 端視圖,嘗試在 RouteConfig 配置路由並創建對應 Area,但訪問自定義起始頁報錯,默認視圖正常。
核心問題在於 Area 註冊順序與路由配置:
AreaRegistration.RegisterAllAreas() 在 RouteConfig.RegisterRoutes 之前調用(Global.asax 中)。AreaRegistration 類,重寫 RegisterArea 方法註冊專屬路由。namespaces 參數指定控制器命名空間,避免衝突。// Global.asax.cs
protected void Application_Start() {
AreaRegistration.RegisterAllAreas(); // 必須最先調用
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
// MobileAreaRegistration.cs
public override void RegisterArea(AreaRegistrationContext context) {
context.MapRoute(
"Mobile_default",
"Mobile/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "Project.Areas.Mobile.Controllers" }
);
}
調整後,PC 端訪問 / 加載主站視圖,Mobile 端訪問 /Mobile/ 加載移動端視圖,路由正確分發。
掌握 Area 機制是實現多端視圖隔離的關鍵。