路由機制概述
1.匹配傳入的請求(該請求不匹配服務器文件系統中文件),並將這些請求映射到控制器操作(Controller中的action方法)
MVC基本的處理流程:來了一個URL請求, 從中找到Controller和Action的值, 將請求傳遞給Controller處理. Controller獲取Model數據對象, 並且將Model傳遞給View, 最后View負責呈現頁面。(說白了,就是來了一個URL,找到一個控制器中的方法)(路由是模式,有參數,通過URL中的參數,就可以對應找到符合這種路由模式的方法)
Routing的作用:
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "GlobalIndex", id = UrlParameter.Optional } );
路由URL模式 |
默認值 |
匹配URL模式的實例 |
{controller}/{action}/{id} |
New {id=“”} |
/albums/display/123 /albums/display |
{controller}/{action}/{id} |
New {controller=“home”, action=“index”, id=“”} |
/albums/display/123 /albums/display /albums / |
public ActionResult Index()
public ActionResult Index(int id)
在頁面中有一個請求
類型 MVCDemo.Controllers.TestController 的 System.Web.Mvc.ActionResult Index()
類型 MVCDemo.Controllers.TestController 的 System.Web.Mvc.ActionResult Index(Int32)
routes.MapRoute("showBlogRoute", "blog/post/{id}", new { controller =“CMS”,action = “Show”,id=“”}); routes.MapRoute("blogRoute", “blog/{action}/{id}", new { controller = "CMS", action = “Index", id = “”}); routes.MapRoute(“DefaultRoute”, // 路由名稱 "{controller}/{action}/{id}", // 帶有參數的 URL new { controller = "Home", action = "Index", id =“”} // 參數默認值 );
routes.MapRoute("simple", "archive/{year}/{month}/{day}", new{controller="blog",action="search",year="2009",month="10",day="10"}, new{ year=@"\d{2}|\d{4}",//只能是兩位或四位數字 month=@"\d{1,2}",//只能使用一位或兩位數字 day=@"\d{1,2}"//只能使用一位或兩位數字 });
2.構造傳出的URL,用來響應控制器中的操作
<div> @Html.ActionLink("點擊","Click","Home"); </div>
RouteCollection. GetVirtualPath方法
方法 |
說明 |
如果具有指定的上下文和參數值,則返回與路由關聯的 URL 路徑的相關信息。 |
|
GetVirtualPath(RequestContext, String, RouteValueDictionary) |
如果具有指定的上下文、路由名稱和參數值,則返回與命名路由關聯的 URL 路徑的相關信息。 |
第一個方法獲得了當前路由的一些信息和用戶指定的路由值(字典)去選擇目標路由。
1. 路由系統然后會循環整個路由表,通過GetVirtualPath方法向每一個路由發問:“Can you generate a URL given these parameters?”
2. 如果答案是Yes,那么就會返回一個VirtualPathData實例,包括URL和與匹配相關的一些其他信息。如果答案是NO,則返回一個Null,路由系統會轉向下一條路由,直到遍歷整個路由表。
舉例:
如果我們在路由機制中定義了一個
routes.MapRoute( name: "test", url: "test/look/{id}", defaults: new { controller = "Home", action = "Click", id = UrlParameter.Optional } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
在視圖中寫:
<div> @Html.ActionLink("測試","look","test"); </div> <div> @Html.ActionLink("點擊","Click","Home"); </div>
最終的結果是 不管點擊哪一個按鈕,都會觸發方法Click
public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { return View(); } public ActionResult Click() { return View(); } }
但是顯示的URL都是
如果我們在地址欄中直接輸入 test/look或者Home/Click 都是正確的。