Search code examples
asp.netlinq-to-sqlwebformsasp.net-mvc-routingasp.net-routing

ASP.net Routing - using database queries in order to determine the physical file, and add extra route data from query results


My question is regarding Page Routing in an ASP.net (VB) Web Forms website.

I need to route to 2 .aspx pages in multiple ways e.g.

routes.MapPageRoute("SEO", "{Title}/{Id}", "~/PageA.aspx")
routes.MapPageRoute("Catalogue", "Issue{IssueNumber}-{PageNumber}", "~/PageA.aspx")

but I need to implement some logic involving database queries (LINQ to SQL) on both routes e.g.

Route 1) Check a bit field, if false then physical file = PageA.aspx, true then PageB.aspx

Route 2) Lookup IssueNumber and PageNumber, retrieve PageId and add to RouteData, set physical file = PageA.aspx

I think the best way of doing this, is to implement an IRouteHandler class but I've not been able to determine:

  • Where to write the database queries in such class
  • How to set the physical file in the class
  • Where/how to add a new value to the route data i.e. PageId
  • Where to check that Id and Number fields are actually integers (constraints?)

I can't find any useful VB.net documentation, any suggestions?

If not I'm going to have to resort to an intermediate .aspx page i.e. Transfer.aspx and then do the database queries and then store return values in session variables and then do a Server.Transfer(PageA.aspx), but this seems like an old-fashioned and inelegant way of doing it. Please help!


Solution

  • Instead of writing your own IRouteHandler I'd suggest implementing your Route class. Override GetRouteData and setup the RouteData object that you return according to your needs.

    Where to write the database queries in such class

    As mentioned above, GetRouteData is the place you are looking for.

    How to set the physical file in the class

    On the RouteData object you return, set RouteHandler to a new PageRouteHandler instance. You can pass the physical path to PageRouteHandler's constructor.

    Where/how to add a new value to the route data i.e. PageId

    Use the Values property of the RouteData object.

    Where to check that Id and Number fields are actually integers (constraints?)

    This should be done with route constraints. The sixth parameter to MapPageRoute for example is a RouteValueDictionary with contraints. To simple check that a parameter is an integer, use a regular expression, like so:

    routes.MapPageRoute("RouteName", _
      "product/{id}", "~/Products.aspx", _
      True, New RouteValueDictionary(), _
      New RouteValueDictionary() From { {"id", "\d+"} })
    

    See the "\d+" at the end? This is the regular expression that the id parameter needs to match.

    If you need more complex constraints you can do that as well, see e.g. http://stephenwalther.com/blog/archive/2008/08/07/asp-net-mvc-tip-30-create-custom-route-constraints.aspx