Mvc3(3)
摘錄于Pro ASP.NET MVC3 Framework一書:
路由匹配:
(一)
1.會預(yù)先定義些路由模式,當(dāng)一個請求路由過來時,路由系統(tǒng)會把這個路由和我們預(yù)先定義的這些模式做匹配,只要匹配成功,路由系統(tǒng)就處理這個URL
2.每個URL中除了主機(jī)名和查詢字符串,其他的部分是用"/"來分成片斷的,路由系統(tǒng)一但匹配成功,就會為解析URL中每個片斷的值,然后將其賦給與其匹配成功的模式中的片斷
3.路由默認(rèn)情況下: ?
A.只和含有相同個數(shù)片斷的模式匹配【多一個或少一個都不行】 ?
B.只要URL和模式匹配上,就為模式中相應(yīng)片斷賦值,而不管這些值具體是什么
4.要改變路由的這種默認(rèn)情況,采用的辦法就是在模式中為片斷設(shè)置默認(rèn)值,如
routes.MapRoute("MyRoute", "{controller}/{action}", ????????????????
?????????????????????????????????????????? ? new { controller = "Home", action = "Index" });
? //這樣就可以匹配含0到2個片斷的路由,URL中若沒有值,就為其采用默認(rèn)值
??//在請求RUL中我們收到的片斷越少,那我們就越多依賴于模式中的默認(rèn)值
?Number of Segments???????????? Example?????????????????????????????????? Maps To
???????? 0????????????????????mydomain.com?????????????????????????????????? controller = Home???? action = Index
???????? 1??????????????????? mydomain.com/Customer???????????????????? controller = Customer action = Index
???????? 2??????????????????? mydomain.com/Customer/List?????????????? controller = Customer action = List
???????? 3??????????????????? mydomain.com/Customer/List/All??????????No match—too many segments
(二)定義靜態(tài)的URL
? 1)URL模式中每個片斷不一定都要是變量(參數(shù)),也可以是指定的靜態(tài)量(不需要賦值) ????
????? Suppose we want to match a URL like this to support URLs that are prefixed with Public ????
??? ? eg:? http://mydomain.com/Public/Home/Index
????? routes.MapRoute("", "Public/{controller}/{action}", new { controller = "Home", action = "Index" }); ????
????? ---這個URL只會匹配帶3個片斷的URL,且第一個片斷必須是Public
??2)還可以定義一個片斷里同時包含靜態(tài)量和變量 ???? ????
????? routes.MapRoute("", "X{controller}/{action}"); ????
????? ---The pattern in this route matches any two-segment URL where the first segment starts with the letter X. The value for controller is taken from the first segment, excluding the X.
???? eg: http://mydomain.com/XHome/Index
?? 3)public static void RegisterRoutes(RouteCollection routes) ???????
?????? { ???????????
???????????? routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
???????????? routes.MapRoute( ???????????
???????????????????????????????????????? "Default", // Route name ???????????
??????????????????????????????????????? "{controller}/{action}/{id}", // URL with parameters?
??????????????????????????????????????? new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ???????????
???????????????????????????????????? );
??????? }
?? //在這個方法里定義的路由是有順序的,依次從上往下匹配,所以應(yīng)該把更明確的路由放在前面,例如:
?? routes.MapRoute("", "X{controller}/{action}");//這個更明確
?? routes.MapRoute("MyRoute", "{controller}/{action}", new { controller = "Home", action = "Index" });
?? routes.MapRoute("", "Public/{controller}/{action}", new { controller = "Home", action = "Index" });
(三)為已經(jīng)存在的路由創(chuàng)建一個別名
之前發(fā)布出去的程序已經(jīng)有了一個路由,且這個路由已被用戶熟悉;后面如果又對該程序進(jìn)行了重構(gòu)了的話,產(chǎn)生了一個新的路由,但又不想改變原先已存在的路由,這時可以用靜態(tài)片斷和默認(rèn)路由來建一個別名,這樣用戶還是用舊的路由,不需要改變,當(dāng)用戶輸入舊的路由時,就會自動跳轉(zhuǎn)到我們建的那個別名路由。 ? ??
eg:?? routes.MapRoute("ShopSchema", "Shop/{action}", new { controller = "Home" }); ??
這樣,當(dāng)用戶請求Shop Controller中的action時,路由系統(tǒng)就會自動轉(zhuǎn)換成請求Home controller中的action
甚至還可以對action取別名,例如:routes.MapRoute("ShopSchema2", "Shop/OldAction", new { controller = "Home", action = "Index" }); ??
//當(dāng)用戶請求Shop/OldAction時,就會轉(zhuǎn)換成請求Home中的Index
?
(四)Defining Custom Segment Variables(自定義片斷變量) ?
不僅僅局限于定義Controller和action,還可以定義自己想要的變量片斷
routes.MapRoute("MyRoute", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "DefaultId" }) ? ?
//This route will match any zero-to-three-segment URL. The contents of the third segment will be assigned to the id variable, and if there is no third segment, the default value will be used.
獲取id的值有兩個方法 ? We can access any of the segment variables in an action method by using the RouteData.Values property.
例如:1.public ViewResult CustomVariable() {
?????????? ViewBag.CustomVariable = RouteData.Values["id"]; ?????
?????????? return View(); ?
}
?????? 2.方法中的參數(shù)名一定要和Route中定義的參數(shù)名相同,否則路由系統(tǒng)會找不到擁有這樣參數(shù)名的方法,從而傳不了值 ?
?????? public ViewResult CustomVariable(string id) { ?????
????????? ViewBag.CustomVariable = id; ?????
????????? return View(); ?
?????? }
(五)Defining Optional URL Segments(定義可選的URL片斷) ?
?一個可選的URL片斷指的是用戶不需要指定,且不需要指定默認(rèn)值的片斷
?routes.MapRoute("MyRoute", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }); ? ? ?
? Number of Segments?????????????????? Example URL??????????????????????????? Maps To
??????? 0??????????????????????????? mydomain.com?????????????????????????????????????? controller = Home???????? action = Index
??????? 1??????????????????????? mydomain.com/Customer??????????????????????????? controller = Customer???? action = Index
??????? 2??????????????????????? mydomain.com/Customer/List???????????????? ???? controller = Customer???? action = List
??????? 3??????????????????????? mydomain.com/Customer/List/All?????????????????controller = Customer???? action = List???? id = All
??????? 4??????????????????????? mydomain.com/Customer/List/All/Delete?????? No match—too many segments
(六)Defining Variable-Length Routes(定義可變長的路由)
??????? 方法:用{*catchall}
?
??????? routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
??
??????? //前面三個片斷依次是為{controller}/{action}/{id}賦值,從第四個開始傳過來的所有的片斷全部賦給{*catchall},
??????? //也就是說這個路由可以匹配任意長度URL
?
(七)通過命名空間(Namespace)來指定使用哪個空間里的Controller
? 如果程序里引用了多個命名空間,不同的空間里可能存在相同的Controller名,這樣在匹配路由時就必須指定匹配哪個空間里的Controller,不然就會報(bào)錯
? 1.routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}", ???????????
???????????????????????????????????????????????? new { controller = "Home", action = "Index", id = UrlParameter.Optional }, ???????????
???????????????????????????????????????????????? new[] { "URLsAndRoutes.Controllers"});//指定命名空間,
? //指定了命名空間后,MVC Framework 會先在URLsAndRoutes.Controllers命名空間里找相應(yīng)的Controller,如果沒找著,MVC Framework接著會在所有可用的命名空間里找
?? 2.routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}", ??????????? n
???????????????????????????????????????????????? new { controller = "Home", action = "Index", id = UrlParameter.Optional }, ???????????
??????????????????????????????????????????????? new[] { "URLsAndRoutes.Controllers", "AdditionalControllers"});
//一個路由里添加了多個命名空間,這些命名空間具有相同的優(yōu)先級,沒有先后順序 ????
//這樣,MVC Framework會試圖解析這兩個命名空間里的所有控制器類,如果這兩個命名空間里存在相同名字的控制器類,那么就會報(bào)錯,所以就不能把這兩個命名空間同時放在一個路由里面,應(yīng)該把它們拆開,單獨(dú)成一個路由,
例如:3.routes.MapRoute("AddContollerRoute", "Home/{action}/{id}/{*catchall}", ???????????
????????????????????????????????????????? new { controller = "Home", action = "Index", id = UrlParameter.Optional }, ???????????
????????????????????????????????????????? new[] { "AdditionalControllers" });
?????????? routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}", ???????????
????????????????????????????????????????? new { controller = "Home", action = "Index", id = UrlParameter.Optional }, ???????????
????????????????????????????????????????? new[] { "URLsAndRoutes.Controllers"});
4.我們也可以指定MVC Framework在我們指定的命名空間里找,如果沒有找到就終止,不會再去另外的命名空間里找 ???? ????
Route myRoute = routes.MapRoute("AddContollerRoute", "Home/{action}/{id}/{*catchall}", ???????????????????????????
????????????????????????? new { controller = "Home", action = "Index", id = UrlParameter.Optional }, ???????????????????????????
????????????????????????? new[] { "AdditionalControllers" }); ???? ????
???????????????????????? myRoute.DataTokens["UseNamespaceFallback"] = false;
//這個設(shè)置將會被傳給負(fù)責(zé)尋找控制器類的控制器工廠,告訴它不用再去找控制器了
?
(八)約束路由
? (1)用正值表達(dá)式來約束路由
???? routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
??????????? new { controller = "Home", action = "Index", id = UrlParameter.Optional },//默認(rèn)路由
??????????? new { controller = "^H.*"},//限制控制器類名是H或h開頭的
??????????? new[] { "URLsAndRoutes.Controllers"});???????
???? //約束限制也像默認(rèn)路由一樣,作為參數(shù),但得放在默認(rèn)路由的后面
? (2)Constraining a Route to a Set of Specific Values(通過設(shè)定值來限定路由)????
???? routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
??????????? new { controller = "Home", action = "Index", id = UrlParameter.Optional },
??????????? new { controller = "^H.*", action = "^Index$ | ^About$"},
??????????? new[] { "URLsAndRoutes.Controllers"});?????
???? //這個路由只匹配controller名是以H或h開頭,action是Index或about
? (3)Constraining a Route Using HTTP Methods
???? We can constrain routes so that they match a URL only when it is requested using a specific HTTP method????
???? routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
??????????? new { controller = "Home", action = "Index", id = UrlParameter.Optional },
??????????? new { controller = "^H.*", action = "Index|About", httpMethod = new HttpMethodConstraint("GET") },
??????????? new[] { "URLsAndRoutes.Controllers" });?????
???? //httpMethod這個屬性名是可以隨便取的,只要傳一個HttpMethodConstraint對象即可
???? //用HTTP方法來限制路由,跟用HttpGet,HttpPost來限制action中的method沒有必然聯(lián)系
???? //路由限制的處理早于action的限制處理????
???? //也可以? httpMethod = new HttpMethodConstraint("GET", "POST")
??(4)Defining a Custom Constraint(省略。。。)
? (5)Routing Requests for Disk Files (路由請求物理文件:such as images, static HTML files, JavaScript libraries, and so on)????
???? 不是所有的路由請求都是請求controller和action的,也可以請求一個物理文件
???? 默認(rèn)情況下,路由系統(tǒng)會首先匹配對物理文件的請求,如果匹配成功,則物理文件被啟用,其它路由則永遠(yuǎn)不會被啟用;如果失敗,則接著匹配其它路由
???? eg:在Content文件夾里創(chuàng)建一個StaticContent.htm,然后在地址欄中輸入?http://localhost:1892/content/StaticContent.htm,就跳到了這個html文件了
???? 我們可以先匹配其他路由,在沒有匹配成功的情況下,會接著去匹配物理文件,也就是改變默認(rèn)情況下的行為,只要設(shè)置:
???? routes.RouteExistingFiles = true;?
???? 這樣一來,當(dāng)輸入http://localhost:1892/content/StaticContent.htm,content就成了controller,StaticContent.htm就成了action, 這時在模式中得為controller及action填上其他值,否則是找不到頁面的
? (6)Bypassing the Routing System(繞開路由系統(tǒng))
???? routes.IgnoreRoute("Content/{filename}.html");
???? //第一個參數(shù)是content,第二個參數(shù)以.html為擴(kuò)展名的路由都將被忽略
?
? (九)Generating Outgoing URLs(生成輸出路由) ?? ??
???(1)
???????A.The simplest way to generate an outgoing URL in a view is to call the Html.ActionLink method within a view, ?? ??
?????? @Html.ActionLink("About this application", "About")
?????? B.Targeting Other Controllers?? ?????
?????? The default version of the ActionLink method assumes that you want to target an action method in the same controller that has caused the view to be rendered. To create an outgoing URL that targets a different controller, you can use a different overload that allows you to specify the controller name
?????? //@Html.ActionLink該方法有好幾個重載,可以傳不同的參數(shù),用的較多的為
????? @Html.ActionLink("linkname", "Index", "Home", new { id = 12 }, new {@class="test"})
????? //形成的html片斷為:<a class="test" href="/Home/Index/12">linkname</a>
????? //從各參數(shù)名和參數(shù)值上看就知道個大概,如果用@Html.ActionLink("About this application", "About"),這個沒有說明是哪個Controller,默認(rèn)是調(diào)用當(dāng)前Controller里的About action
?? (2)當(dāng)為一個屬性賦上值,且這個屬性跟路由片斷不匹配,那么這個屬性值將會被追加在輸出URL的后面作為查詢串,
?????? 例如:??@Html.ActionLink("About this application", "About", new { id = "MyID", myVariable = "MyValue" }) ???? ????
???????It generates the following HTML:
?????? <a href="/Home/About?id=MyID&myVariable=MyValue">About this application</a> ????
?????? //相當(dāng)于多傳遞了一個串
?? (3)@Html.ActionLink("About this application", "Index", "Home") ???? ????
?????? 如果路由如下: ???? routes.MapRoute("Default", // Route name ???????????????
?????????????????????????????????????????????????????????? "{controller}/{action}/{id}", // URL with parameters ???????????????
?????????????????????????????????????????????????????????? new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ???????????
????????????????????????????????? );
???? 當(dāng)Html.ActionLink中提供的action名和controller名與默認(rèn)路由提供的相同時,那么在形成輸出路由時,路由系統(tǒng)會忽略Html.ActionLink中提供的值,形成html片斷為
???? <a href="/">About this application</a>
?? (4)Generating URLs (and Not Links)【用Url.Action方法】 ????
?????? 生成一個URL,不帶html標(biāo)記,Html.ActionLink生成的URL是在<a>標(biāo)記里面的 ???? ????
?????? ---we can use the Url.Action method to generate just the URL and not the surrounding HTML
?????? eg:?? My URL is: @Url.Action("Index", "Home", new { id = "MyId" })[調(diào)用Index方法] ???? ????
?????? 生成的結(jié)果是:My URL is: /Home/Index/MyId
?????? //這種情況用在:只是想僅僅顯示一個URL
????? //The Url.Action method works in the same way as the Html.ActionLink method, except that it generates only the URL.
??? (5)在action方法中生成輸出路由
???? public ViewResult MyActionMethod() {
???????????? string myActionUrl = Url.Action("Index", new { id = "MyID" });
???????????? string myRouteUrl = Url.RouteUrl(new { controller = "Home", action = "Index" });
???????????? ... do something with URLs...
????? }
????? //最常見的情況是先生成一個路由,然后再進(jìn)行跳轉(zhuǎn),可以用RedirectToAction方法實(shí)現(xiàn) ?????
???? public ActionResult MyActionMethod() { ???????????? return RedirectToAction("Index"); ????? }?????
?????public ActionResult MyOtherActionMethod() {???????return RedirectToRoute(new { controller = "Home", action = "Index", id = "MyID" }); ????? }??
???? //這里換成RedirectToAction方法是同樣的效果
?
轉(zhuǎn)載于:https://www.cnblogs.com/notebook2011/archive/2012/12/05/2804217.html
總結(jié)
- 上一篇: 局域网PING的TIME值都超高的一种解
- 下一篇: poj 2299 Ultra-Quick