惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

罗磊的独立博客
Cisco Talos Blog
Cisco Talos Blog
C
Check Point Blog
博客园_首页
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Martin Fowler
Martin Fowler
Recorded Future
Recorded Future
S
Security @ Cisco Blogs
L
LINUX DO - 最新话题
博客园 - 司徒正美
P
Privacy International News Feed
G
Google Developers Blog
I
Intezer
Hacker News - Newest:
Hacker News - Newest: "LLM"
博客园 - 聂微东
The GitHub Blog
The GitHub Blog
C
Cybersecurity and Infrastructure Security Agency CISA
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Scott Helme
Scott Helme
K
Kaspersky official blog
I
InfoQ
Y
Y Combinator Blog
T
The Blog of Author Tim Ferriss
Webroot Blog
Webroot Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
大猫的无限游戏
大猫的无限游戏
D
Docker
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
Microsoft Azure Blog
Microsoft Azure Blog
Spread Privacy
Spread Privacy
量子位
H
Hacker News: Front Page
Simon Willison's Weblog
Simon Willison's Weblog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
SecWiki News
SecWiki News
S
Security Affairs
Latest news
Latest news
人人都是产品经理
人人都是产品经理
C
CERT Recently Published Vulnerability Notes
S
Security Archives - TechRepublic
V
Visual Studio Blog
T
Troy Hunt's Blog
S
Secure Thoughts
F
Fortinet All Blogs
V
V2EX
The Register - Security
The Register - Security
J
Java Code Geeks
MongoDB | Blog
MongoDB | Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO

博客园 - zhangh

[转]铁路订票网站个人的设计浅见 新写了一个Web即时通程序,基于HTTP长连接的服务器推技术。 .NET Framework 3.5 SP1安装时下载文件问题及精简方法2(转) [转] javascript基础知识大集锦(2) 迪士尼近期将拓展中国三线城市的市场 迪士尼礼品批发网 Web Service WSE 3.0 creation time in the timestamp cannot be in the future 局域网内机器访问服务器数据库连接,访问Web Service需要密码 - zhangh - 博客园 Web Service "Unsupported media type error" ubuntu下配置eclipse3.3 ubuntu下配置tomcat Ubuntu下配置samba实现文件夹共享 Open Source URL Rewriter for .NET / IIS / ASP.NET 要实现动态加载JS脚本有4种方法 - zhangh - 博客园 window.opener - zhangh - 博客园 在WinForm中使用Web Services 来实现 软件 自动升级( Auto Update ) (C#) 多线程断点续传研究之二 多线程断点续传研究之一 winform登录窗口的正确操作办法
使用XML文件来动态配置ASP.NET MVC的Route规则 - zhangh - 博客园
zhangh · 2009-06-20 · via 博客园 - zhangh

一般情况下,我们都是直接在Global.asax.cs文件中直接写上Route规则的,例如:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default",                                              // Route name
        "{controller}/{action}/{id}",                           // URL with parameters
        new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
    );
}

这样在我们的程序编译、部署后,我们想修改这个Route规则就得重新修改程序中Global.asax.cs文件中的Route规则=>编译=>部署,不可以做到动态配置。

其实我们可以做到动态配置,我们可以将这个Route规则写到一个XML文件中,例如这样:

<RouteConfiguration>
  <ignore>
    <!--忽略对.axd文件的Route,直接处理-->
    <add url="{resource}.axd/{*pathInfo}" >
      <constraints>
        <!--添加约束,value是乱写的,只为演示-->
        <add name="resource" value="\w" />
      </constraints>
    </add>
  </ignore>
  <map>
    <route name="Post" url="Post/{id}" controller="Home" action="Post" >
      <parameters>
        <!--添加参数默认值-->
        <!--添加约束,id必须为GUID-->
        <add name="id" value="" constraint="[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}" />
      </parameters>
    </route>
    <route name="Default" url="{controller}/{action}/{id}" controller="Home" action="Index" >
      <parameters>
        <add name="id" value="" />
      </parameters>
    </route>
  </map>
</RouteConfiguration>

我们例如Web.config中的configSection来写我们的自定义配置节,来配置上面的XML文件。首先,我需要写一个定义的configSection,他继承自ConfigurationSection,如下:

public class MvcRouteConfigurationSection : ConfigurationSection
{
    [ConfigurationProperty("ignore", IsRequired=false)]
    public IgnoreCollection Ignore
    {
        get
        {
            return (IgnoreCollection)(this["ignore"]);
        }
    }

    [ConfigurationProperty("map", IsRequired=false)]
    public RoutingCollection Map
    {
        get
        {
            return (RoutingCollection)(this["map"]);
        }
    }
}

然后我们写一个扩展方法来自定义将我们配置好的Route规则写入到程序路由表中:

public static void MapRoute(
    this System.Web.Routing.RouteCollection routes, 
    MvcRouteConfigurationSection section )
{
    // Manipulate the Ignore List
    foreach(IgnoreItem ignoreItem in section.Ignore)
    {
        RouteValueDictionary ignoreConstraints = new RouteValueDictionary();

        foreach (Constraint constraint in ignoreItem.Constraints)
            ignoreConstraints.Add(constraint.Name, constraint.Value);

        IgnoreRoute(routes, ignoreItem.Url, ignoreConstraints);
    }

    // Manipluate the Routing Table
    foreach (RoutingItem routingItem in section.Map)
    {
        RouteValueDictionary defaults = new RouteValueDictionary();
        RouteValueDictionary constraints = new RouteValueDictionary();

        if (routingItem.Controller != string.Empty)
            defaults.Add("controller", routingItem.Controller);

        if (routingItem.Action != string.Empty)
            defaults.Add("action", routingItem.Action);

        foreach (Parameter param in routingItem.Paramaters)
        {
            defaults.Add(param.Name, param.Value);
            if (!string.IsNullOrEmpty(param.Constraint))
            {
                constraints.Add(param.Name, param.Constraint);
            }
        }

        MapRoute(routes, routingItem.Name, routingItem.Url, defaults, constraints);
    }
}

然后在web.config中的configSections配置节下加入我们写好的MvcRouteConfigurationSection :

<section name="RouteConfiguration" type="MvcXmlRouting.MvcRouteConfigurationSection"/>

最后,在Global.asax.cs中用我们刚才写的MapRoute扩展方法来注册我们的Route规则:

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        MvcRouteConfigurationSection section = 
            (MvcRouteConfigurationSection)ConfigurationManager.GetSection("RouteConfiguration");

        routes.MapRoute(section);
    }

    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
    }
}

OK,大功告成。Enjoy! by Q.Lee.lulu.

原文见:ASP.NET MVC Routing Using XML Custom Configuration Settings

本文的示例代码在原文的代码基础上添加了对约束(constraints)的支持!