views:

490

answers:

2

I there a simple way when using ASP.NET 4.0 routing with Web Forms to produce a route that will act as some kind of wildcard?

It seems to me that within WebForms, you have to specify a route for every page - I am looking for some kind of generic route that can be used where nothing specific is required, perhaps mapping directly from path to path so...

http://somedomain.com/folder1/folder2/page would possibly map to folder1/folder2/page.aspx

Any suggestions?

Thanks

+4  A: 

You can match all remaining routes like this:

routes.MapPageRoute("defaultRoute", "{*value}", "~/Missing.aspx");

In this case, we know all routes, and want to send anything else to a "missing"/404 page. Just be sure to put this as the last route, since it is a wildcard and will catch everything.

Alternatively you could register a route the same way, but internally does mapping to a page, like this:

routes.Add(new Route("{*value}", new DefaultRouteHandler()));

That handler class would do your wildcard mapping, something like this:

public class DefaultRouteHandler : IRouteHandler
{
  public IHttpHandler GetHttpHandler(RequestContext requestContext)
  { 
    //Url mapping however you want here:
    var pageUrl = requestContext.RouteData.Route.Url + ".aspx";

    var page = BuildManager.CreateInstanceFromVirtualPath(pageUrl, typeof(Page)) 
               as IHttpHandler;
    if (page != null)
    {
      //Set the <form>'s postback url to the route
      var webForm = page as Page;
      if (webForm != null) 
         webForm.Load += delegate { webForm.Form.Action = 
                                    requestContext.HttpContext.Request.RawUrl; };
    }
    return page;
  }
}

This is broken a bit in odd places to prevent horizontal scrolling, but you get the overall point. Again, make sure this is the last route, otherwise it'll handle all your routes.

Nick Craver
A: 

Nick, there doesn't seem to be a "Url" property in the RouteBase object i.e. "requestContext.RouteData.Route.Url", do you know off-hand how to get the Url? I took a quick look through the class documentation and nothing jumped out.

Thanks

Dean