Mvc3(3)
摘錄于Pro ASP.NET MVC3 Framework一書(shū):
路由匹配:
(一)
1.會(huì)預(yù)先定義些路由模式,當(dāng)一個(gè)請(qǐng)求路由過(guò)來(lái)時(shí),路由系統(tǒng)會(huì)把這個(gè)路由和我們預(yù)先定義的這些模式做匹配,只要匹配成功,路由系統(tǒng)就處理這個(gè)URL
2.每個(gè)URL中除了主機(jī)名和查詢(xún)字符串,其他的部分是用"/"來(lái)分成片斷的,路由系統(tǒng)一但匹配成功,就會(huì)為解析URL中每個(gè)片斷的值,然后將其賦給與其匹配成功的模式中的片斷
3.路由默認(rèn)情況下: ?
A.只和含有相同個(gè)數(shù)片斷的模式匹配【多一個(gè)或少一個(gè)都不行】 ?
B.只要URL和模式匹配上,就為模式中相應(yīng)片斷賦值,而不管這些值具體是什么
4.要改變路由的這種默認(rèn)情況,采用的辦法就是在模式中為片斷設(shè)置默認(rèn)值,如
routes.MapRoute("MyRoute", "{controller}/{action}", ????????????????
?????????????????????????????????????????? ? new { controller = "Home", action = "Index" });
? //這樣就可以匹配含0到2個(gè)片斷的路由,URL中若沒(méi)有值,就為其采用默認(rèn)值
??//在請(qǐng)求RUL中我們收到的片斷越少,那我們就越多依賴(lài)于模式中的默認(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模式中每個(gè)片斷不一定都要是變量(參數(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" }); ????
????? ---這個(gè)URL只會(huì)匹配帶3個(gè)片斷的URL,且第一個(gè)片斷必須是Public
??2)還可以定義一個(gè)片斷里同時(shí)包含靜態(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 ???????????
???????????????????????????????????? );
??????? }
?? //在這個(gè)方法里定義的路由是有順序的,依次從上往下匹配,所以應(yīng)該把更明確的路由放在前面,例如:
?? routes.MapRoute("", "X{controller}/{action}");//這個(gè)更明確
?? routes.MapRoute("MyRoute", "{controller}/{action}", new { controller = "Home", action = "Index" });
?? routes.MapRoute("", "Public/{controller}/{action}", new { controller = "Home", action = "Index" });
(三)為已經(jīng)存在的路由創(chuàng)建一個(gè)別名
之前發(fā)布出去的程序已經(jīng)有了一個(gè)路由,且這個(gè)路由已被用戶熟悉;后面如果又對(duì)該程序進(jìn)行了重構(gòu)了的話,產(chǎn)生了一個(gè)新的路由,但又不想改變?cè)纫汛嬖诘穆酚?#xff0c;這時(shí)可以用靜態(tài)片斷和默認(rèn)路由來(lái)建一個(gè)別名,這樣用戶還是用舊的路由,不需要改變,當(dāng)用戶輸入舊的路由時(shí),就會(huì)自動(dòng)跳轉(zhuǎn)到我們建的那個(gè)別名路由。 ? ??
eg:?? routes.MapRoute("ShopSchema", "Shop/{action}", new { controller = "Home" }); ??
這樣,當(dāng)用戶請(qǐng)求Shop Controller中的action時(shí),路由系統(tǒng)就會(huì)自動(dòng)轉(zhuǎn)換成請(qǐng)求Home controller中的action
甚至還可以對(duì)action取別名,例如:routes.MapRoute("ShopSchema2", "Shop/OldAction", new { controller = "Home", action = "Index" }); ??
//當(dāng)用戶請(qǐng)求Shop/OldAction時(shí),就會(huì)轉(zhuǎn)換成請(qǐng)求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的值有兩個(gè)方法 ? 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)會(huì)找不到擁有這樣參數(shù)名的方法,從而傳不了值 ?
?????? public ViewResult CustomVariable(string id) { ?????
????????? ViewBag.CustomVariable = id; ?????
????????? return View(); ?
?????? }
(五)Defining Optional URL Segments(定義可選的URL片斷) ?
?一個(gè)可選的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(定義可變長(zhǎng)的路由)
??????? 方法:用{*catchall}
?
??????? routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
??
??????? //前面三個(gè)片斷依次是為{controller}/{action}/{id}賦值,從第四個(gè)開(kāi)始傳過(guò)來(lái)的所有的片斷全部賦給{*catchall},
??????? //也就是說(shuō)這個(gè)路由可以匹配任意長(zhǎng)度URL
?
(七)通過(guò)命名空間(Namespace)來(lái)指定使用哪個(gè)空間里的Controller
? 如果程序里引用了多個(gè)命名空間,不同的空間里可能存在相同的Controller名,這樣在匹配路由時(shí)就必須指定匹配哪個(gè)空間里的Controller,不然就會(huì)報(bào)錯(cuò)
? 1.routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}", ???????????
???????????????????????????????????????????????? new { controller = "Home", action = "Index", id = UrlParameter.Optional }, ???????????
???????????????????????????????????????????????? new[] { "URLsAndRoutes.Controllers"});//指定命名空間,
? //指定了命名空間后,MVC Framework 會(huì)先在URLsAndRoutes.Controllers命名空間里找相應(yīng)的Controller,如果沒(méi)找著,MVC Framework接著會(huì)在所有可用的命名空間里找
?? 2.routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}", ??????????? n
???????????????????????????????????????????????? new { controller = "Home", action = "Index", id = UrlParameter.Optional }, ???????????
??????????????????????????????????????????????? new[] { "URLsAndRoutes.Controllers", "AdditionalControllers"});
//一個(gè)路由里添加了多個(gè)命名空間,這些命名空間具有相同的優(yōu)先級(jí),沒(méi)有先后順序 ????
//這樣,MVC Framework會(huì)試圖解析這兩個(gè)命名空間里的所有控制器類(lèi),如果這兩個(gè)命名空間里存在相同名字的控制器類(lèi),那么就會(huì)報(bào)錯(cuò),所以就不能把這兩個(gè)命名空間同時(shí)放在一個(gè)路由里面,應(yīng)該把它們拆開(kāi),單獨(dú)成一個(gè)路由,
例如: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在我們指定的命名空間里找,如果沒(méi)有找到就終止,不會(huì)再去另外的命名空間里找 ???? ????
Route myRoute = routes.MapRoute("AddContollerRoute", "Home/{action}/{id}/{*catchall}", ???????????????????????????
????????????????????????? new { controller = "Home", action = "Index", id = UrlParameter.Optional }, ???????????????????????????
????????????????????????? new[] { "AdditionalControllers" }); ???? ????
???????????????????????? myRoute.DataTokens["UseNamespaceFallback"] = false;
//這個(gè)設(shè)置將會(huì)被傳給負(fù)責(zé)尋找控制器類(lèi)的控制器工廠,告訴它不用再去找控制器了
?
(八)約束路由
? (1)用正值表達(dá)式來(lái)約束路由
???? routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
??????????? new { controller = "Home", action = "Index", id = UrlParameter.Optional },//默認(rèn)路由
??????????? new { controller = "^H.*"},//限制控制器類(lèi)名是H或h開(kāi)頭的
??????????? new[] { "URLsAndRoutes.Controllers"});???????
???? //約束限制也像默認(rèn)路由一樣,作為參數(shù),但得放在默認(rèn)路由的后面
? (2)Constraining a Route to a Set of Specific Values(通過(guò)設(shè)定值來(lái)限定路由)????
???? routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
??????????? new { controller = "Home", action = "Index", id = UrlParameter.Optional },
??????????? new { controller = "^H.*", action = "^Index$ | ^About$"},
??????????? new[] { "URLsAndRoutes.Controllers"});?????
???? //這個(gè)路由只匹配controller名是以H或h開(kāi)頭,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這個(gè)屬性名是可以隨便取的,只要傳一個(gè)HttpMethodConstraint對(duì)象即可
???? //用HTTP方法來(lái)限制路由,跟用HttpGet,HttpPost來(lái)限制action中的method沒(méi)有必然聯(lián)系
???? //路由限制的處理早于action的限制處理????
???? //也可以? httpMethod = new HttpMethodConstraint("GET", "POST")
??(4)Defining a Custom Constraint(省略。。。)
? (5)Routing Requests for Disk Files (路由請(qǐng)求物理文件:such as images, static HTML files, JavaScript libraries, and so on)????
???? 不是所有的路由請(qǐng)求都是請(qǐng)求controller和action的,也可以請(qǐng)求一個(gè)物理文件
???? 默認(rèn)情況下,路由系統(tǒng)會(huì)首先匹配對(duì)物理文件的請(qǐng)求,如果匹配成功,則物理文件被啟用,其它路由則永遠(yuǎn)不會(huì)被啟用;如果失敗,則接著匹配其它路由
???? eg:在Content文件夾里創(chuàng)建一個(gè)StaticContent.htm,然后在地址欄中輸入?http://localhost:1892/content/StaticContent.htm,就跳到了這個(gè)html文件了
???? 我們可以先匹配其他路由,在沒(méi)有匹配成功的情況下,會(huì)接著去匹配物理文件,也就是改變默認(rèn)情況下的行為,只要設(shè)置:
???? routes.RouteExistingFiles = true;?
???? 這樣一來(lái),當(dāng)輸入http://localhost:1892/content/StaticContent.htm,content就成了controller,StaticContent.htm就成了action, 這時(shí)在模式中得為controller及action填上其他值,否則是找不到頁(yè)面的
? (6)Bypassing the Routing System(繞開(kāi)路由系統(tǒng))
???? routes.IgnoreRoute("Content/{filename}.html");
???? //第一個(gè)參數(shù)是content,第二個(gè)參數(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該方法有好幾個(gè)重載,可以傳不同的參數(shù),用的較多的為
????? @Html.ActionLink("linkname", "Index", "Home", new { id = 12 }, new {@class="test"})
????? //形成的html片斷為:<a class="test" href="/Home/Index/12">linkname</a>
????? //從各參數(shù)名和參數(shù)值上看就知道個(gè)大概,如果用@Html.ActionLink("About this application", "About"),這個(gè)沒(méi)有說(shuō)明是哪個(gè)Controller,默認(rèn)是調(diào)用當(dāng)前Controller里的About action
?? (2)當(dāng)為一個(gè)屬性賦上值,且這個(gè)屬性跟路由片斷不匹配,那么這個(gè)屬性值將會(huì)被追加在輸出URL的后面作為查詢(xún)串,
?????? 例如:??@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)于多傳遞了一個(gè)串
?? (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)路由提供的相同時(shí),那么在形成輸出路由時(shí),路由系統(tǒng)會(huì)忽略Html.ActionLink中提供的值,形成html片斷為
???? <a href="/">About this application</a>
?? (4)Generating URLs (and Not Links)【用Url.Action方法】 ????
?????? 生成一個(gè)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
?????? //這種情況用在:只是想僅僅顯示一個(gè)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...
????? }
????? //最常見(jiàn)的情況是先生成一個(gè)路由,然后再進(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值都超高的一种解
- 下一篇: MVC中helper的用法。