MVC路由作用
解析URL的作用,将用户输入的URL地址中的 控制器名称 和 Action 名称解析出来,寻找相应的页面显示给用户。
案例分析
在调试MVC例子的时候,程序每次执行都是从Global.asax中的Application_Start方法中启动执行。
1、注册路由,将新建的Route对象添加到RouteTable对象中,RouteTable对象用于存储所有的路由规则。
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);//注册路由
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
2、执行路由选择
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional }
);
}
上述代码中的Routes对象有两个方法,
一、是IgnoreRoute。IgnoreRoute方法是用来定义不需要路由规则处理的网址,指定后缀名为.axd等格式的网址不通过MVC执行。
二、是MapRoute,其中MapRoute方法,就是用来识别URL的,其中Default是路由的名称,后面的“{controller}/{action}/{id}”就是我们需要解析出来的东西,一个是controller名称,Action名称,以及Id名称。不写的话,controller默认的是Home,action默认的是Index,而id默认为空。
例如,localhost/Home/Index,这个URL地址,通过路由解析将去执行HomeController里面的Index方法,将相应的页面传递给用户。