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

推荐订阅源

奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
WordPress大学
WordPress大学
博客园 - 【当耐特】
Engineering at Meta
Engineering at Meta
IT之家
IT之家
Apple Machine Learning Research
Apple Machine Learning Research
小众软件
小众软件
美团技术团队
S
SegmentFault 最新的问题
The GitHub Blog
The GitHub Blog
Martin Fowler
Martin Fowler
Recorded Future
Recorded Future
H
Help Net Security
aimingoo的专栏
aimingoo的专栏
Y
Y Combinator Blog
博客园_首页
A
About on SuperTechFans
MongoDB | Blog
MongoDB | Blog
阮一峰的网络日志
阮一峰的网络日志
V
Visual Studio Blog
D
DataBreaches.Net
人人都是产品经理
人人都是产品经理
大猫的无限游戏
大猫的无限游戏
B
Blog
The Register - Security
The Register - Security
I
InfoQ
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
雷峰网
雷峰网
Last Week in AI
Last Week in AI
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
月光博客
月光博客
酷 壳 – CoolShell
酷 壳 – CoolShell
Blog — PlanetScale
Blog — PlanetScale
N
Netflix TechBlog - Medium
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
有赞技术团队
有赞技术团队
Stack Overflow Blog
Stack Overflow Blog
Jina AI
Jina AI
Security Archives - TechRepublic
Security Archives - TechRepublic
Hacker News - Newest:
Hacker News - Newest: "LLM"
U
Unit 42
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
W
WeLiveSecurity
Latest news
Latest news
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
博客园 - 叶小钗
L
Lohrmann on Cybersecurity
博客园 - Franky
Recent Commits to openclaw:main
Recent Commits to openclaw:main
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO

博客园 - 大鱼

发送HTML表单数据:URL编码的表单数据 MVC核心功能组件和简介 emulator-5554 disconnected! Cancelling '*** activity launch'! 安卓模拟器启动报错 AJAX 调用 WEBSERVICE的例子,包括对XML数据的处理,包含源码下载 类似ipone的滑动开锁功能--拖动后能自动回滚到起始位置--BackgroundWorker 批处理文件BAT安装WINDOWS服务带参数和设置目录 正则表达式30分钟入门教程(第二版) 【转载】 gridview 在列表中对信息进行增删改,通过VIEWSTATE进行缓存,然后一次性将数据提交到服务器端。 Excel VBA 应用 --批量修改选中区域单元格的时间数据,自动为时间值加1月 CELL值=CELL值 + DateAdd(“m”,1,date) - 大鱼 基于Windows下的Web性能测试和压力测试-zhuan team foundation server 安装 图片上传控件 SQL Server 2005异地备份 - 转-已验证 SQL Server 2005 镜像功能实现 - 转 -已验证 如何在VS 2005 SP1中使用VS的web服务器运行一个相对于根目录“/”的网站 xmlhttp-JS-实现用户是否注册无刷新验证 VS项目模板(项模板)制作--针对ASP.NET站点页面使用 安装用于 Team Foundation Server(单服务器部署)的 Microsoft Windows SharePoint Services ---TFS安装问题集 Aspect inside castle 实现 AOP
使用XML文件来动态配置ASP.NET MVC的Route规则
大鱼 · 2013-01-12 · via 博客园 - 大鱼

一般情况下,我们都是直接在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)的支持!

本文示例代码下载:XmlRout.Web.rar

转自:http://www.cnblogs.com/QLeelulu/archive/2008/11/24/1340212.html