ASP.NET Web Forms 4.0 中的双向 Routing 支持

  • 2009-03-07
  • 本文字数:781 字

    阅读完需:约 3 分钟

.NET Framework 3.5 SP1 已经包含了 ASP.NET Routing 引擎。现在微软已经在 ASP.NET WebForms 4.0 中增加了对 Routing 引擎更好的支持,它使用表达式构造器进行双向 Routing。

Channel 9 刚发布了一个 10-4 的新视频,展示如何在 ASP.NET 4.0 中使用这个新功能

下面是视频中展示的一段代码。他们使用了一个经典示例,展示如何将 Product.aspx?category=Jerseys 映射至 Product/Jerseys。在使用 ASP.NET Routing 引擎时,我们可以在 Application_Start 中向 RouteTable 添加这样的映射:


RouteTable.Routes.Add("Product",
   new Route("Product/{name}", 
   new PageRouteHandler("~/Product.aspx")));

目前为了得到双向的 Routing 支持,用户必须对 Query String 进行 URL 重写。不过,使用 ASP.NET 4.0 时,用户可以注册如下的表达式构造器(expression builder):


<system.web>
 <compilation>
   <expressionBuilders ...>
     <add expressionPrefix="RouteUrl" 
          type="System.Web.Compilation.RouteUrlExpressionBuilder" />
     <add expressionPrefix="RouteValue"
          type="System.Web.Compilation.RouteValueExpressionBuilder" />
   </expressionBuilders>
 </compilation>
</system.web>

第一个表达式用于生成 URL 而第二个用于获取 Route 值。在 aspx 页面中可以使用 $ 符号来访问表达式:

<asp:HyperLink NavigationUrl="<%$ RouteUrl:RouteName=Product, name=Jerseys" 
    Text="Jerseys" 
    runat="server" />

如果要获取 name 属性中的值,用户可以使用 Route 对象而不是 Request 对象:

RouteData.Values["name"];或使用表达式构造器:

<%$ RouteValue:name %>用户可以利用 ASP.NET Routing 引擎和新的双向支持将 URL 和物理上的 Web Form 解耦,以便支持对搜索引擎更友好的 URL。

查看英文原文: Bi-Directional Routing Support in ASP.NET Web Forms 4.0