WebForms custom / dynamic routing

前端 未结 2 736
时光取名叫无心
时光取名叫无心 2021-01-07 09:44

I\'m using Phil Haack\'s URL routing for WebForms and I would like to define a route that\'s \"dynamic.\" Let\'s say I have this route:

\"{any}.aspx\" -- goes to -->

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-07 10:48

    My solution -- unless somebody comes up with a more elegant one -- was to modify the WebFormRouteHandler class in the WebFormRouting project to accept a custom predicate.

    public WebFormRouteHandler(string virtualPath, bool checkPhysicalUrlAccess, Func custom)
    

    Then inside the class I would store the custom parameter into private CustomVirtualPath property. To use it, I had to change GetSubstitutedVirtualPath to this:

    public string GetSubstitutedVirtualPath(RequestContext requestContext)
    {
      string path = VirtualPath;
    
      if (CustomVirtualPath != null)
      {
        path = CustomVirtualPath(requestContext);
      }
    
      if (!path.Contains("{")) return path;
    
      //Trim off ~/
      string virtualPath = path.Substring(2);
    
      Route route = new Route(virtualPath, this);
      VirtualPathData vpd = route.GetVirtualPath(requestContext, requestContext.RouteData.Values);
      if (vpd == null) return path;
      return "~/" + vpd.VirtualPath;
    }
    

    For the project to compile we need to change WebFormRoute and WebFormRouteExtensions to allow the passing of the custom parameter down the chain. When all done I can write this in global.asax.cs

    routes.MapWebFormRoute("All", "{any}.aspx", "~/", false,
                             context =>
                               {
                                 return ((string)context.RouteData.Values["any"] == "test"
                                           ? "~/PageProcessor.aspx"
                                           : "~/DifferentPageProcessor.aspx");
                               });
    

    Of course the body of the lambda expression should look up the URL from some other place (database or cache).

提交回复
热议问题