ASP.NET MVC 3 - Customizable SEO Friendly Routes

I 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 contain all the characters and replace some of them.

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

Rules:

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

Any help would be greatly appreciated!

+5
source share
1 answer

Seems like the 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 as follows:

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

Now you only need to fulfill your SEO requirements in the function SEOifythat I left. By the way, you can get inspiration from the fooobar.com/questions/29019 / ... path for question headers.

+6

All Articles