首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

ASP.NET MVC 區域註冊解決自定義起始頁路由問題

     編輯:程式設計疑難解答

問題背景

項目需區分 PC 和 Mobile 端視圖,嘗試在 RouteConfig 配置路由並創建對應 Area,但訪問自定義起始頁報錯,默認視圖正常。

解決方案

核心問題在於 Area 註冊順序與路由配置:

  1. 確保 AreaRegistration.RegisterAllAreas() 在 RouteConfig.RegisterRoutes 之前調用(Global.asax 中)。
  2. 各 Area 內需有 AreaRegistration 類,重寫 RegisterArea 方法註冊專屬路由。
  3. 路由配置中設置 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 機制是實現多端視圖隔離的關鍵。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved