3. URL路由

URL路由

原文 : http://quickstarts.asp.net/3-5-extensions/mvc/URLRouting.aspx

1. 介绍

2. 定义URL路由
URL路由包括一个URL模式定义,在模式定义中,"{}"定义占位符,"/"和"."分割各个字符串.
当URL请求字符串被URL模式解析时,占位符和具体的值组成"键值对".
一般,URL路由在Global.asax文件的Application_Start方法中被定义.
示例代码:
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routes)
{
routes.Add(new Route("Category/{action}/{categoryName}",new CategoryRouteHandler() ));
}

3. 为路由参数设置默认值.
若不设置默认值,则URL路由要求所有占位符都必须赋值才能匹配.
示例代码:
public static void RegisterRoutes(RouteCollection routes)
{
routes.Add(new Route("Category/{action}/{categoryName}", new CategoryRouteHandler())
{
Defaults = new RouteValueDictionary
{
{"categoryName", "food"}, {"action", "show"}
}

}
);
}

4. 捕获未知数量的参数.
使用"*"通配符,如:"query/{queryname}/{*queryvalues}",
使用它可以匹配"/query/select/bikes/onsale", 则queryvalues = "bikes/onsale".

5. 为URL模式添加约束.
示例代码:
public static void RegisterRoutes(RouteCollection routes)
{
routes.Add(new Route("{locale}/{year}" , new ReportRouteHandler())
{
Constraints = new RouteValueDictionary
{
{"locale", "{a-z}{2}-{A-Z}{2}"},{year, @"d{4}"}
}

}
);
}

6. 使用URL路由信息创建链接.
示例代码:
HyperLink1.NavigateUrl = RouteTable.Routes.GetVirtualPath
(context,
new RouteValueDictionary {
{ "categoryName", "beverages" },
{"action", "summarize" }}
).VirtualPath;
将获得一个包含"Category/summarize/beverages"的超链接.
posted on 2008-05-06 16:56  Na57  阅读(817)  评论(0编辑  收藏  举报