2013-01-09 41 views
1

我有一個webforms-project,我使用System.Web.Routing.RouteCollection.MapPageRoute來重寫URL,但我有一些動態URL的問題。我的網址可能是這樣的;MapPageRoute中的通配符

/folder/city-1-2-something.aspx 

和的MapPageRoute這個看起來像這樣

routeCollection.MapPageRoute("CompanyCity", "folder/city-{id}-{pid}-{title}.aspx", "~/mypage.aspx"); 

但我已經意識到,某些URL可能看起來像這樣

/folder/city-2-2-something-something.aspx 
/folder/city-2-2-something-something-something.aspx 
/folder/city-2-2-something-something-something-something.aspx 

和這些都不是我的路由正確毫無遺漏 - 第一個示例將以結果id = 2-2和pid =結束,而不是id = 2和pid = 2結束。

{title}並不重要 - 只使用{id}和{pid}。我有幾個類似的路線到特定的文件夾,所以據我可以我不能使用一個捕獲所有。但我該如何解決這個問題?

回答

1

下面的簡單RouteConfig包含一個TestRoute,它完全符合您的需求。僅此而已,所以它在某種意義上是非常糟糕的代碼。

但這個想法是現在可以使用正則表達式,可以很容易地滿足您的需求。 (命名組「id」(?<id>\d)和「pid」(?<pid>\d)只匹配數字(\d)爲什麼他們只會匹配到下一個破折號。)

希望它可以有一些靈感。

using System.Text.RegularExpressions; 
using System.Web; 
using System.Web.Mvc; 
using System.Web.Routing; 

namespace InfosoftConnectSandbox 
{ 
    public class RouteConfig 
    { 
     class TestRoute : RouteBase 
     { 
      Regex re = new Regex(@"folder/city-(?<pid>\d)-(?<id>\d)-.*"); 

      public override RouteData GetRouteData(HttpContextBase httpContext) 
      { 
       var data = new RouteData(); 

       var url = httpContext.Request.Url.ToString(); 

       if (!re.IsMatch(url)) 
       { 
        return null; 
       } 

       foreach (Match m in re.Matches(url)) 
       { 
        data.Values["pid"] = m.Groups["pid"].Value; 
        data.Values["id"] = m.Groups["id"].Value; 
       } 

       data.RouteHandler = new PageRouteHandler("~/mypage.aspx"); 

       return data; 
      } 

      public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) 
      { 
       return new VirtualPathData(this, "~/mypage.aspx"); 
      } 
     } 

     public static void RegisterRoutes(RouteCollection routes) 
     { 
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

      routes.Add(new TestRoute()); 

      routes.MapRoute(
       name: "Default", 
       url: "{controller}/{action}/{id}", 
       defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
      ); 
     } 
    } 
}