Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3 - Custom SEO friendly routes

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!

like image 871
šljaker Avatar asked Dec 12 '11 16:12

šljaker


1 Answers

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.

like image 64
Darin Dimitrov Avatar answered Sep 27 '22 17:09

Darin Dimitrov