在开始之前,我们再来重申一下WebForm与MVC的本质区别:请求的url不同。
WebForm请求的是一个具体的页面,当用户请求具体的aspx页面时,服务器会对该页面中的内容一行一行的解析(碰到服务器脚本语言还会执行),最后形成响应流重新写回到浏览器,再由浏览器对该响应流进行解析(依照W3C标准),最终将用户请求的页面呈现出来;
MVC请求的是控制器下面的某个Action,该方法会接着调用业务逻辑层取出数据来交给控制器,控制器再将数据交给具体的视图显现出来。
MVC的核心就是通过路由模块实现的,下面我们就对这个模块进行简单的学习。不对之处欢迎指出、共同学习改进。
我们可以进行路由规则的注册,下面举例说明了几个。
一、系统默认路由
下面给出了一些代码,方便大家比较学习
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "User", action = "Create", id = UrlParameter.Optional } // Parameter defaults
);
Url格式为:http://localhost:1024/User/Create 对应规则为:{controller}/{action}/{id} 。详细匹配为:http://localhost:1024/User/Create/1 去掉主机域名,剩下对应的就是Controller和Action了。通过Routing组件解析这个Url,Controller是User,Action是Create,传递过去的Id是1。
二、不使用默认路由规则
routes.MapRoute(
"不使用默认路由规则", // Route name
"{controller}/{id}-{action}", // URL with parameters
new { controller = "User", action = "Create", id = UrlParameter.Optional } // Parameter defaults
);
实例:http://localhost:1024/User/1-Create 设置传递的路由参数为 1
三、带命名空间的Url路由规则
routes.MapRoute(
"不使用默认路由规则", // Route name
"{controller}/{id}-{action}", // URL with parameters
new { controller = "User", action = "Create", id = UrlParameter.Optional } // Parameter defaults
new String{"MvcDemo.Controllers"} //设置命名空间
);
实例:http://localhost:1024/User/1-Create
四、带约束的路由规则
routes.MapRoute(
"Rule1",
"{controller}/{action}-{Year}-{Month}-{Day}}",
new { controller = "User", action = "Create", Year = "2000", Month = "11", Day = "1" },
new { Year = @"^\d{5}", Month = @"\d{6}" }
);
实例:http://localhost:1024/User/Create-2010-01-21
五、带名称空间,带约束,带默认值的路由规则
routes.MapRoute(
"Rule1",
"Admin/{controller}/{action}-{Year}-{Month}-{Day}",
new { controller = "User", action = "Create", Year = "2000", Month = "11", Day = "1" },
new { Year = @"^\d{5}", Month = @"\d{6}" },
new string[] { "MvcDemo.Controllers" }
);
实例:http://localhost:14039/Admin/User/Create-2010-01-21
六、捕获所有的路由
routes.MapRoute(
"All", // 路由名称
"{*Vauler}", // 带有参数的 URL
new { controller = "User", action = "Create", id = UrlParameter.Optional } // 参数默认值
);
七、Global.asax剩余部分的说明:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");是忽略这个规则的Url
AreaRegistration.RegisterAllAreas();//注册所有的Areas
RegisterRoutes(RouteTable.Routes);//注册我们写的规则
八、使用RouteDebug辅助类进行调试
1.添加辅助类应用
下载辅助类dll组件,将该dll文件添加到项目中,在文件中添加该引用
2.添加测试语句
在Application_Start方法中添加一句话
RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);//测试语句
上面的代码测试时,我的路由表中只有一个默认的路由规则,加上一条匹配所以Url的路由规则,一共两条。有兴趣的可以多添加几条路由规则进行测试。
九、总结
根据上面的讲解,我们知道,可以注册多条路由规则,那么就有了一个路由规则的注册前后的问题。当我们根据Url进行路由匹配时会首先从路由表的第一条路由规则开始匹配,一旦匹配就不会进行下面的匹配。同样是第二条匹配,就不会进行余下几条的路由匹配。但是会有那么一种情况出现:匹配的不是我们希望的路由,这样就会导致错误。在实际使用过程中,我们应该把那些我们希望经常使用的路由规则写在路由表的前面。想要了解关于路由的更多信息可以参考计算机网络。