ASP.NET MVC 入门 3、Routing2010-08-21Q.Lee.lulu在一个route中,通过在大括号中放一个占位符来定义( { and } )。当解析 URL的时候,符号"/"和"."被作为一个定义符来解析,而定 义符之间的值则匹配到占位符中。route定义中不在大括号中的信息则作为常量值 。下面是一些示例URL:
| Valid route definitions | Examples of matching URL | 
| {controller}/{action}/{id} | /Products/show/beverages | 
| {table}/Details.aspx | /Products/Details.aspx | 
| blog/{action}/{entry} | /blog/show/123 | 
| {reporttype}/{year}/{month}/{day} | /sales/2008/1/5 | 
通常,我们在Global.asax文件中的Application_Start事件中添加routes,这 确保routes在程序启动的时候就可用,而且也允许在你进行单元测试的时候直接 调用该方法。如果你想在单元测试的时候直接调用它,注册该routes的方法必需 是静态的同时有一个RouteCollection参数。下面的示例是Global.asax中的代码,演示了添加一个包含两个URL参数action 和 categoryName的Route对象:
public static void RegisterRoutes(RouteCollection routes)
{
//忽略对.axd文件的Route,也就是和WebForm一样直接去访问.axd文件
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Category",// Route 的名称
"Category/{action}/{categoryName}", // 带有参数的URL
new { controller = "Category", action = "Index", categoryName = "4mvc" }// 设置默认的参数
);
}
protected void Application_Start()
{
//在程序启动的时候注册我们前面定义的Route规则
RegisterRoutes(RouteTable.Routes);
}
在这里我不打算再详细去讲解。以下只是简单的说明一下。忽略对某类URL的Routing://忽略对.axd文件的Route,也就是和WebForm一样直接去访问.axd文件routes.IgnoreRoute("{resource}.axd/{*pathInfo}");添加约束条件,支持正则表达式。例如我们需要对id参数添加一个必须为数字 的条件:
routes.MapRoute(
  "Default",
  "{controller}/{action}/{id}",
  new {controller="Home",action="Index",id=""}, 
  new{id=@"[d]*"}//id必须为数字
);