上面介绍的是最简单的一种定义方式。当然我们可以建立更复杂的规则。其中就包括设定规则的默认值以及设定规则的正则表达式。
UrlRouting高级应用
预计效果:
当我访问/a/b.aspx时就会转到Default.aspx?category = a&action = b在页面上显示category:aaction:b亦如果我访问/chsword/xxxx.aspx就会转到Default.aspx?category = chsword&action = xxxx就会显示category:chsword action:xxxx
如果访问/chsword/就会转到 Default.aspx?category=chsword&action=index就会显示
category:chsword
action:index
首先我建立一个Route
routes.Add( " Default " , new Route( " {category}/{action}.aspx " , new RouteValueDictionary( new { file = " Default " , category = " home " , action = " index " }), new MyRouteHandler() ) ); 当然IHttpHandler的处理方式也要有所改变
为了方便查看我使用了下方法:
context.Server.Execute( string .Format( " /{0}.aspx?category={1}&action={2} " , RequestContext.RouteData.Values.ContainsKey( " file " ) ? RequestContext.RouteData.Values[ " file " ].ToString() : " default " , RequestContext.RouteData.Values.ContainsKey( " category " ) ? RequestContext.RouteData.Values[ " category " ].ToString() : "" , RequestContext.RouteData.Values.ContainsKey( " action " ) ? RequestContext.RouteData.Values[ " action " ].ToString() : "" ) );
即/a/b.aspx是映射到Default.aspx?category=a&action=b
在Default.aspx中写如下代码:
category: <% = Request.Params[ " category " ] %> < br /> action: <% = Request.Params[ " action " ] %>
以显示传入的参数。
如果在IIS中设置Index.aspx时就算输入/a/也会访问到/a/index.aspx,即默认的会按RouteValueDictionary中设置的值自动补全
UrlRouting使用正则表达式规则
UrlRouting在定义的时候也可以按正则的规则来进行定义。
routes.Add( " zz " , new Route( " {category}/{action}.chs " , new RouteValueDictionary( new { file = " Default " , category = " home " , action = " 1 " }), new RouteValueDictionary( new { action = " [\\d]+ " }), new MyRouteHandler() ) );
以上代码规定了action只能是数字则访问/a/1.chs可以正常访问。
而访问/a/b.chs则会显示未找到资源。
当然这是里可以使用更高级的正则表达式。
UrlRouting的技巧
排除UrlRouting的方法:
System.Web.Routing默认提供了一个IRouteHandler-,经过它处理的URL不会被做任何处理
通常使用方法如下:
routes.Add(new Route("{resource}.axd/{*pathInfo}", new StopRoutingHandler()));
RouteHandler工厂:
其实IRouteHandler可以实现一个RouteHandler的简单工厂。
public class RouteHandlerFactory : IRouteHandler { string Name { get ; set ; } public RouteHandlerFactory( string name){ this .Name = name;} #region IRouteHandler 成员 public IHttpHandler GetHttpHandler(RequestContext requestContext) { if ( this .Name == " mypage " ) return new MyPage(requestContext); if ( this .Name = " mypage1 " ) return new MyPage1(requestContext); } #endregion }
规定HTTP verbs,这里要使用System.Web.Routing中的
void Application_Start( object sender, EventArgs e) { RegisterRoutes(RouteTable.Routes);} public static void RegisterRoutes(RouteCollection routes){ string [] allowedMethods = { " GET " , " POST " }; HttpMethodConstraint methodConstraints = new HttpMethodConstraint(allowedMethods); Route reportRoute = new Route( " {locale}/{year} " , new ReportRouteHandler()); reportRoute.Constraints = new RouteValueDictionary { { " httpMethod " , methodConstraints } }; routes.Add(reportRoute);}
Demo程序代码下载: