天天看點

System.Web.Routing入門及進階 下篇

<a href="http://www.cnblogs.com/chsword/archive/2008/08/27/system_web_routing_1.html">System.Web.Routing入門及進階 上篇</a>

上面介紹的是最簡單的一種定義方式。當然我們可以建立更複雜的規則。其中就包括設定規則的預設值以及設定規則的正規表達式。

預計效果:

當我通路/a/b.aspx時就會轉到Default.aspx?category=a&amp;action=b在頁面上顯示

category:a

action:b

亦如果我通路/chsword/xxxx.aspx就會轉到Default.aspx?category=chsword&amp;action=xxxx就會顯示

category:chsword

action:xxxx

如果通路/chsword/就會轉到 Default.aspx?category=chsword&amp;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}&amp;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&amp;action=b

在Default.aspx中寫如下代碼:

 category:&lt;%=Request.Params["category"] %&gt;&lt;br /&gt;

   action:&lt;%=Request.Params["action"] %&gt;

以顯示傳入的參數。

如果在IIS中設定Index.aspx時就算輸入/a/也會通路到/a/index.aspx,即預設的會按RouteValueDictionary中設定的值自動補全

UrlRouting在定義的時候也可以按正則的規則來進行定義。

            routes.Add(

                "zz",

                new Route("{category}/{action}.chs",

                    new RouteValueDictionary(

                        new {

                            file = "Default",

                            category = "home",

                            action = "1"

                        }),

                        new RouteValueDictionary(

                            action = "[\\d]+"

                    new MyRouteHandler()

            );

以上代碼規定了action隻能是數字則通路/a/1.chs可以正常通路。

而通路/a/b.chs則會顯示未找到資源。

當然這是裡可以使用更進階的正規表達式。

通常使用方法如下:

routes.Add(new Route("{resource}.axd/{*pathInfo}", new StopRoutingHandler()));

其實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

    }

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程式代碼下載下傳: