當我們訪問一個url的時候,程序首先做的事情是global.ascx中 先把路由全部註冊
然後url根據註冊的路由 從上到下 去匹配,匹配到適合的就不在往下進行就按照第一個匹配的路由
去相應的控制器中進行訪問。
話說如此,可是如何進行匹配路由?
路由分段這個概念
最基礎的就是
在應用程序中的App_Start 下的RouteConfig.cs中
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "PeonyTours.Controllers" }
);
可以理解爲 三段 controller、action、id
但是如果有默認的段的話 也就是可以url不說明這個段 這個對三段都進行了說明 可以0-3段都匹配
MVC框架從URL獲取到變量的值都可以通過RouteData.Values["xx"],這個集合訪問
如果控制器一樣的話就需要命名空間區別一下優先級順序。比如區域裏的home和應用程序中的home控制器 如果不命名空間標記,就會報錯因爲匹配的時候 這倆個看起來一樣就不知道匹配哪個了。
這篇文章更詳細可看 https://www.cnblogs.com/itliuyang/p/6872027.html
global
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}