views:

88

answers:

2

Is there an article somewhere explaining exactly how the route matching works, and what it is capable of?

for example, how would i write a route to catch everything?

so:

/
/something
/something/else
/something/else/again

all get mapped to the same controller action, with the url as a parameter?

{*anything}

doesnt seem to work. can it not handle slashes inside arguments?

Thanks

+1  A: 

I have had to handle that in past using this method:

public ActionResult Something(string anything)
{
     var anythings = anything.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

And this route:

"something/{*anything}"

And to catch everything. This is probably a smell but...

public class HomeController : Controller
{
   public ActionResult Show(string anything)
   {
      Response.Write(anything);
      return null;
   }

Then before the Default route...

routes.MapRoute("anything", "{*anything}", new {controller="Home",action="Show"});
mxmissile
what about the root, or things that dont begin with "something"?
Andrew Bullock
updated my answer
mxmissile
+3  A: 

The code below catches almost everything.

http://www.mysite.com/

for instance would still be routed to default.aspx,I think. But something like

http://www.mysite.com/some/page/that/doesnt/exist

would be caught by the TestRouteHandler. The {*fields} route specifier should wind up in the RequestContext.RouteData object passed to the router so you can do whatever you want. However, at that point, you're basically implementing a rewrite engine.

public class Routes
{
    public static void Register(RouteCollection routes)
    {
        // setup legacy url routing
        routes.Add(new Route("{*fields}",new TestRouteHandler()));
    }
}

public class TestRouteHandler : IRouteHandler
{
    public virtual IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        Page page = BuildManager.CreateInstanceFromVirtualPath("/default.aspx", typeof(Page)) as Page;
        return page;
    }

}

alternatively, you can specify a top-level route like

    routes.Add(new Route("dave/{*fields}",new TestRouteHandler()));

which will catch items like.

http://www.mysite.com/dave
http://www.mysite.com/dave/test/parameter
http://www.mysite.com/dave/virtually/infinite/number/of/items/goes/here
David Lively
i was doing this but it wasnt working, now it is :s wierd. must have been one of those friday moments! thanks for clarification
Andrew Bullock