[译] 在Web Forms 中使用ASP.NET Routing

时间:2022-10-28 16:55:10

本文将以最少的代码想你展示一下的效果:

自定义RUL而不依赖于物理文件名。

使用标记或者代码产生基于route 参数的URL 。

如何获得标记或者代码路由过来的参数。

创建Routes

void Application_Start(object sender, EventArgs e)
   {
       RegisterRoutes(RouteTable.Routes);
   }

 

我们不妨看下RouteTable 这个类的定义:

public class RouteTable
 {
   private static RouteCollection _instance = new RouteCollection();

   /// <summary>
   /// Gets a collection of objects that derive from the <see cref="T:System.Web.Routing.RouteBase"/> class.
   /// </summary>
   ///
   /// <returns>
   /// An object that contains all the routes in the collection.
   /// </returns>
   public static RouteCollection Routes
   {
     get
     {
       return RouteTable._instance;
     }
   }

   static RouteTable()
   {
   }
 }

先添加第一个Route

routes.MapPageRoute("",
           "SalesReportSummary/{year}",
           "~/sales.aspx");

这是一个一目了然的映射。

routes.MapPageRoute("SalesRoute",
            "SalesReport/{locale}/{year}",
            "~/sales.aspx");

这个也是一样。

routes.MapPageRoute("ExpensesRoute",
           "ExpenseReport/{locale}/{year}/{*extrainfo}",
           "~/expenses.aspx", true,
           new RouteValueDictionary {
               { "locale", "US" },
               { "year", DateTime.Now.Year.ToString() } },
           new RouteValueDictionary {
               { "locale", "[a-z]{2}" },
               { "year", @"\d{4}" } });

       routes.MapPageRoute("ProductRoute",
           "ProductPage/{productname}/{*culture}",
            "~/product.aspx");

可以给Route 添加约束和默认值。

获得Route 参数

路由简单,获得路由过来的参数同样也很简单。

LocaleLiteral.Text = Page.RouteData.Values["locale"] == null ?
           "All locales" : Page.RouteData.Values["locale"].ToString();

       YearLiteral.Text = Page.RouteData.Values["year"].ToString();