5

I've defined the following route:

routes.MapRoute(
    null,
    "foo/{id}/{title}",
    new { controller = "Boo", action = "Details" }
);

When I call this method:

Url.Action("Details", "Boo", new { id = article.Id, title = article.Title })

I get the following URL:
http://localhost:57553/foo/1/Some%20text%20Š

I would like to create a new route that will lowercase all characters and replace some of them.

e.g.
http://localhost:57553/foo/1/some-text-s

Rules:

Uppercase -> lowercase    
' ' -> '-'
'Š' -> 's'
etc.

Any help would be greatly appreciated!

šljaker
  • 7,294
  • 14
  • 46
  • 80

1 Answers1

6

Seems like a perfect candidate for a custom route:

public class MyRoute : Route
{
    public MyRoute(string url, object defaultValues)
        : base(url, new RouteValueDictionary(defaultValues), new MvcRouteHandler())
    {
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        values = new RouteValueDictionary(values);
        var title = values["title"] as string;
        if (!string.IsNullOrEmpty(title))
        {
            values["title"] = SEOify(title);
        }
        return base.GetVirtualPath(requestContext, values);
    }

    private string SEOify(string title)
    {
        throw new NotImplementedException();
    }
}

which will be registered like this:

routes.Add(
    "myRoute",
    new MyRoute(
        "foo/{id}/{title}",
        new { controller = "Boo", action = "Details" }
    )
);

Now all you have to do is to implement your SEO requirements in the SEOify function that I left. By the way you could get some inspiration from the way StackOverflow does it for the question titles.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Awesome! +1. What about custom routes vs URL helpers? I found similar solution on SO a few years ago (but can't find it now) and now everyone are suggesting URL helpers over custom router? – šljaker Dec 12 '11 at 16:30
  • @šljaker, I don't understand what you are asking when you say `custom routes vs URL helpers`. Are you asking which is better: use a custom route that will perform this or write custom helpers such as Html.ActionLink, Url.Action, ...? If this is the case then a custom route is much better as you centralize your entire routing logic and the way your urls look like in the routes which is where this should be done instead of dispersing such logic all around your codease. It's much easier to modify it in a single location and all standard HTML helpers will use it automatically over the entire app. – Darin Dimitrov Dec 12 '11 at 16:33