TAGS :Viewed: 16 - Published at: a few seconds ago

[ How do I create a Route that matches parameters when they contain slashes (/)? ]

I have only a route in my ASP.NET MVC App:

routes.MapRoute(
    "Post",
    "post/{url}",
    new { controller = "Blog", action = "Post" }
);

When I go to /post/MyTestBlahBlah it matches correctly, and calls Blog.Post(url).

However, when I go to /post/2010/03/MyTestBlahBlah I get a 404.

How do I make the route match urls even with there are slashes in them?

Note: MY URLs are not fixed as /year/month/post, they can be in any format, which is why I want to match all URLs. I need it to be capture and passed into the controller (as opposed to using "*") to aid testing - I do not want the Controller to read the URL from the Response object.

Answer 1


In your case, I would add a new route before that route described there:

routes.MapRoute(
    "Post_Verbose",
    "post/{year}/{month}/{url}",
    new { controller = "Blog", action = "Post" });

Or simply:

routes.MapRoute(
    "Post",
    "post/{*url}",
    new { controller = "Blog", action = "Post" });

Answer 2


I managed to find a solution here. You need to put a "*" in front of the paramter name ({*url}). Ironically, the first thing I tried was {url*}!

routes.MapRoute(
    "Post",
    "post/{*url}",
    new { controller = "Blog", action = "Post" }
);