Routing在ASP.NET MVC中是非常核心的技术,属于ASP.NET MVC几大核心技术之一,在使用Routing之前,得先引入System.Web.Routing,但其实不用这么麻烦,因为在创建ASP.NET MVC项目时,编译器已经自动添加该引入了。
首先来看看Routing有什么能力使得它是ASP.NET MVC的几大技术之一,即Routing的两大作用:
1、在客户端浏览器将URL提交到服务器后,先经过Routing,Routing把URL(如:http://localhost:39495/Home/Index)解析成:1):http://localhost:39495(网站网址)。2)Home(控制器)。3)Index(Action方法)。然后根据此解析内容对比到对应的方法。
2、相应适当的网址给浏览器,将View中的超链接相应给浏览器。
新建一个ASP.NET MVC项目后,编译器会自动生成一些项目所需的文件,当然,有些文件对于项目来说是多余,根据来需要剁掉,但这不是此次内容多说的。
Roting默认路由是由编译器自动生成的,其位置在解决方案根目录的App_Start文件夹下,展开该文件夹就能够看到本尊RouteConfig.cs配置文件。该配置文件内容如下所示:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 using System.Web.Routing; 7 8 namespace MvcGuestBook 9 { 10 public class RouteConfig 11 { 12 public static void RegisterRoutes(RouteCollection routes) 13 { 14 routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 15 16 routes.MapRoute( 17 name: "Default", 18 url: "{controller}/{action}/{id}", 19 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 20 ); 21 } 22 } 23 }
现在就来分析一下这段代码的功能:
14行中IgnoreRoute方法作用是忽略(Ignore)路由参数RouteValue,也即是比对到以{resource}.axd/{*pathInfo}的路由规则将会被忽略掉。
17行表示定义Route名称,这里为“Default”。
18行定义了路由规则,即请求先到达controller,后到达Action,返回参数id.
19行定义了默认路由规则,即如果没有键入相应的controller、Action,则系统默认到达的控制器是Home,Action是Index。
原文:http://www.cnblogs.com/cenwei/p/4937721.html