问题
I've been exploring the System.Web.Routing namespace, playing with constraints and such, but I can't see a way to implement this.
I'm working on an ASP.NET website (non-WAP, non-MVC) using the WebPages/Razor framework.
I'm trying to implement a form of "nested routing", where a route can contain child routes that are only attempted if the parent matches; each child attempting to match the "remainder" of the URI. A "depth-first" route match search, if you will.
routes.Add(new ParentRoute("{foo}/{*remainder}", new[] {
new ParentRoute("{bar}/{*remainder}", new[] {
new Route("{baz}"),
new Route("{zip}"),
}),
new ParentRoute("{qux}/{*remainder}", new[] {
new Route("{baz}"),
new Route("{zip}"),
}),
));
I've excluded necessary constraints/handlers (among other parameters) for brevity.
In any case, each step descending through the tree would match the {*remainder}
tail of the URI. If a branch fails, it moves up and on to the next, essentially testing something like:
foo
foo/bar
foo/bar/baz
foo/bar/zip
foo/qux
foo/qux/baz
foo/qux/zip
Now, I'm certainly not asking "please to write teh codez", but rather a gesture in the right direction.
Where would I want to be looking in the API in order to begin implementing such a feature? I can find countless tutorials and information on writing routes, constraints, etc., but not on extending the routing engine.
Addendum
I'll just keep adding as warrants
Please note, I am aware that URL generation from a "routing tree" such as this would be complicated; it is not something I intend to implement.
I just realized a sort of iterative route generation could suffice; so I guess I'll post that as a possible answer shortly.Nope, it wouldn't. Too many edge cases.
回答1:
I have the following code but there is one point I am not sure how you want to handle it: do you know how many child can have a route at the maximum?
In the Global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.Add(new Route("test/{path}", new RouteValueDictionary { { "path", string.Empty } }, new TestingRouteHandler()));
}
The TestingRoutHandler class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Routing;
using System.Web;
using System.Web.UI;
using System.Web.Compilation;
namespace WebApplication1
{
class TestingRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
//This is where you should treat the request, test if the file exists and if not, use the parent part of the url
string aspxFileName = string.Format("~/{0}.aspx", requestContext.HttpContext.Request.Url.PathAndQuery.Replace("/", string.Empty));
return (IHttpHandler)BuildManager.CreateInstanceFromVirtualPath(aspxFileName, typeof(Page)) as Page;
}
}
}
来源:https://stackoverflow.com/questions/13971468/depth-first-nested-routing-in-an-asp-net-website