首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET MVC 進階配置:自定義 ConfigurationSection 為路由註冊強型別配置

     編輯:關於ASP.NET

將路由規則、URL 重寫規則等遷移出 Global.asax 代碼,存放於 web.config 專屬區段,實現「配置即代碼、熱更新無需重編譯」。本文示範完整實作流程。

核心類別體系

  • ConfigurationSection:根區段,對應 <routeConfig>
  • ConfigurationElementCollection:集合元素,對應 <routes>
  • ConfigurationElement:單一路由元素,屬性映射 name, url, controller, action, constraints

配置檔結構

<configuration>
  <configSections>
    <section name="routeConfig" 
      type="Core.Configuration.Operation.RouteConfigSection, Core.Configuration" />
  </configSections>
  <routeConfig configSource="config\routes.config" /> <!-- 外部檔案,支援熱更新 -->
</configuration>

外部 routes.config 範例

<routeConfig>
  <routes>
    <add name="Product" url="Product/{id}" controller="Product" action="Details" 
         constraints="id=\d+" />
    <add name="Blog" url="Blog/{year}/{month}" controller="Blog" action="Archive"
         constraints="year=\d{4};month=\d{2}" />
  </routes>
</routeConfig>

關鍵實作代碼

public class RouteConfigSection : ConfigurationSection {
    [ConfigurationProperty("routes")]
    public RouteElementCollection Routes => (RouteElementCollection)base["routes"];
}

[ConfigurationCollection(typeof(RouteElement), AddItemName="add")]
public class RouteElementCollection : ConfigurationElementCollection {
    protected override ConfigurationElement CreateNewElement() => new RouteElement();
    protected override object GetElementKey(ConfigurationElement element) 
        => ((RouteElement)element).Name;
}

public class RouteElement : ConfigurationElement {
    [ConfigurationProperty("name", IsRequired=true, IsKey=true)]
    public string Name { get => (string)base["name"]; set => base["name"] = value; }

    [ConfigurationProperty("url", IsRequired=true)]
    public string Url { get => (string)base["url"]; set => base["url"] = value; }

    [ConfigurationProperty("controller", IsRequired=true)]
    public string Controller { get => (string)base["controller"]; set => base["controller"] = value; }

    [ConfigurationProperty("action", IsRequired=true)]
    public string Action { get => (string)base["action"]; set => base["action"] = value; }

    [ConfigurationProperty("constraints", DefaultValue="")]
    public string Constraints { get => (string)base["constraints"]; set => base["constraints"] = value; }
}

Global.asax 讀取並註冊

protected void Application_Start() {
    var section = (RouteConfigSection)ConfigurationManager.GetSection("routeConfig");
    foreach (RouteElement elem in section.Routes) {
        var constraints = ParseConstraints(elem.Constraints); // 解析 "id=\d+" → RouteValueDictionary
        RouteTable.Routes.MapRoute(elem.Name, elem.Url, 
            new { controller = elem.Controller, action = elem.Action }, constraints);
    }
}

進階優勢

  • 熱更新:修改 routes.config 立即生效(ASP.NET 自動重啟應用域)。
  • 權限分離:運維人員可調整路由無需開發介入。
  • 環境差異:Dev/Staging/Prod 使用不同 configSource 指向各自配置檔。
  • 型別安全:編譯期檢查屬性名稱,避免字串拼寫錯誤。

擴展方向

  • 支援 namespaces、dataTokens、handler 等進階屬性。
  • 整合 IRouteConstraint 型別名稱,動態載入約束類別。
  • 建立管理後台 UI,提供路由增刪改查、啟停、測試匹配功能。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved