user1027620
user1027620

Reputation: 2785

ASP.NET Routing, Simple issue

I have the below:

    routes.MapPageRoute("RouteToPages", "{PageName}", "~/Page.aspx");

    routes.MapPageRoute("RouteToProducts", "products", "~/Products.aspx");
    routes.MapPageRoute("RouteToProduct", "product/{ProductName}", "~/Products.aspx");

Of course as you might have guessed, I can never go to /products on my website because it will automatically redirect me to ~/Page.aspx. Is there a way to fix this and allow routing to other "directories" while maintaining a dynamic page name on the root of my domain ?

Thanks!

Upvotes: 2

Views: 138

Answers (3)

Eonasdan
Eonasdan

Reputation: 7765

You should be able to flip the routes around

routes.MapPageRoute("RouteToProducts", "products", "~/Products.aspx");
routes.MapPageRoute("RouteToProduct", "product/{ProductName}", "~/Products.aspx");
routes.MapPageRoute("RouteToPages", "{PageName}", "~/Page.aspx");
  • /products should got to /products.aspx
  • /product/foo should got to /products.aspx
  • /foo should got to /pages.aspx

routes are first come first serve. If it makes route 1, that's the one it takes. {PageName} matches everything so naturally it will take it first

Upvotes: 0

Dave Zych
Dave Zych

Reputation: 21887

Put the routes in reverse order - most specific to lease specific. When redirecting to a route, it will search until it finds a match, then it stops.

routes.MapPageRoute("RouteToProduct", "product/{ProductName}", "~/Products.aspx");
routes.MapPageRoute("RouteToProducts", "products", "~/Products.aspx");
routes.MapPageRoute("RouteToPages", "{PageName}", "~/Page.aspx");

Upvotes: 1

Lawrence Johnson
Lawrence Johnson

Reputation: 4043

I would normally write an HttpModule to handle this, but I would imagine that the rules should be first matching. Try this:

routes.MapPageRoute("RouteToProducts", "products", "~/Products.aspx");
routes.MapPageRoute("RouteToPages", "{PageName}", "~/Page.aspx");
routes.MapPageRoute("RouteToProduct", "product/{ProductName}", "~/Products.aspx");

Upvotes: 1

Related Questions