所謂URL路由,它負責將進入的瀏覽器請求映射到特定的
MVC控制器操作。
從請求中捕獲數據。(URL正向映射(inbound)到Controller和Action))
從數據生成虛擬路徑。(Controller和Action反向映射(outbound)並構造URL))
靈活性:由於URL是對物理文件路徑的反映,意味着如果物理文件的路徑發生了改變(比如改變了文件的目錄結構或者文件名),原來基於該文件鏈接將變得無效。
可讀性:在很多情況下,URL不僅僅需要能夠訪問正確的網絡資源,還需要具有很好的可讀性,最好的URL應該讓我們一眼就能看出針對它訪問的目標資源是什麼。請求地址與物理文件緊密綁定讓我們完全失去了定義高可讀性URL的機會。
SEO優化:對於網站開發來說,爲了迎合搜索引擎檢索的規則,我們需要對URL進行有效的設計使之能易於被主流的引擎檢索收錄。如果URL完全與物理地址關聯,這無異於失去了SEO優化的能力。
簡單的路由規則:
Routing中,我們可以通過大括號({})擴住佔位符(有稱為“URL”參數)。分析URL時講/和.字符解釋為分隔符,講Routing定義中不是分隔符和不在大括號中的值試為常量值,講從兩個分隔符之間提取的值分配給佔位符。
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Store", action = "Index", id = UrlParameter.Optional }
有效的URL (字面值與請求進行精確匹配,而url參數是貪婪匹配)
路由 | 請求的URL |
路由數據的結果 |
{filename}.{ext} |
/Foo.xml.aspx |
Filename=“Foo.xml” Ext=aspx |
My{title}-{cat} |
/MyHouse-dwelling |
title=“House” Cat=“dwelling” |
{fool}xyz{bar} |
/xyzxyzxyzblah |
Fool=“xyzxyz” Bar=“blah” |
帶名稱空間,約束和默認值的路由規則
路由機制會自動地使用”^”和”$”符號包裝指定的約束表達式,以確保能夠精確地匹配參數值。
routes.MapRoute(“Rule1”,
”{controller}/{action}-{Year}-{Month}-{Day}”,
new{controller=“Home”,action=“index”,Year=“2010”,
Month=“04”,Day=“21”},
new {Year=@”\d{4}”,Month=@“\d{2}”},
new string[]{“MvcDemo.Controllers”}//在區域路由使用
);
捕獲所有的路由
Routes.MapRoute(
“All”,
“query/{query_name}/{*value}”
new {controller=“Home”,action=“Index”, id = UrlParameter.Optional }
)
URL | 參數值 |
/query/select/a/b/c |
Value=“a/b/c” |
/query/select/a/b |
Value=“a/b” |
/query/select/ |
Value=“” |
自定義路由約束
//自定義路由約束要實現IrouteConstraint接口
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if(values.Count>0){
int k;
if(Int32.TryParse(values["id"].ToString(),out k)){
return true;
}
}
return false;
}
routes.MapRoute(“Detail”,“{controller}/{action}/{id}”,new {Controller=“News”,action=“Detail”,id=2},new {id=new SelfConstraint()});
溢出參數
當代碼中指定的參數比需要的要多。那些額外的參數將作爲查詢字符串參數附加到生成的URL之後
public static void RegisterRoutes(RouteCollection routes) {
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Default", id = UrlParameter.Optional }
);
@Url.RouteUrl(new {controller=“Report”,action=“List”,page=123})
// 生成的URL:/Report/List?page=2
Route Class
URL正向映射(inbound)與反向映射(outbound )
參考:http://www.cyqdata.com/aspnetmvc/article-detail-52921
URLRouting Debugger(http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx)
使用URLRouting Debugger可以快速檢驗一個URL是否被某個規則採納
RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);