所謂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);