How to route tree-structured URLs with ASP.NET Routing?

Posted by Venemo on Stack Overflow See other posts from Stack Overflow or by Venemo
Published on 2010-05-22T23:10:03Z Indexed on 2010/05/22 23:20 UTC
Read the original article Hit count: 366

Hello Everyone,

I would like to achieve something very similar to this question, with some enhancements.

There is an ASP.NET MVC web application.

I have a tree of entities.
For example, a Page class which has a property called Children, which is of type IList<Page>. (An instance of the Page class corresponds to a row in a database.)

I would like to assign a unique URL to every Page in the database.
I handle Page objects with a Controller called PageController.

Example URLs:

http://mysite.com/Page1/
http://mysite.com/Page1/SubPage/
http://mysite.com/Page/ChildPage/GrandChildPage/

You get the picture.
So, I'd like every single Page object to have its own URL that is equal to its parent's URL plus its own name.
In addition to that, I also would like the ability to map a single Page to the / (root) URL.

I would like to apply these rules:

  1. If a URL can be handled with any other route, or a file exists in the filesystem in the specified URL, let the default URL mapping happen
  2. If a URL can be handled by the virtual path provider, let that handle it
  3. If there is no other, map the other URLs to the PageController class

I also found this question, and also this one and this one, but they weren't of much help, since they don't provide an explanation about my first two points.

I see the following possible soutions:

  • Map a route for each page invidually.
    This requires me to go over the entire tree when the application starts, and adding an exact match route to the end of the route table.
  • I could add a route with {*path} and write a custom IRouteHandler that handles it, but I can't see how could I deal with the first two rules then, since this handler would get to handle everything.

So far, the first solution seems to be the right one, because it is also the simplest.

I would really appreciate your thoughts on this.

Thank you in advance!

© Stack Overflow or respective owner

Related posts about .NET

Related posts about ASP.NET