Search code examples
c#asp.net-mvc-3seoslug

How to add a 'text slug' to a page url in MVC3?


Check out what StackOverflow does:

http://stackoverflow.com/questions/8933768/c-sharp-boolean-outside-method-wont-read

The URL works without the final decorator, that is mainly used for SEO purposes.

I want something like this on my ASP.Net MVC3 application.

Assuming on the Article table I have a field Slug nvarchar(1024) not null, how do I push this out of the routing engine so it appears when someone visits the link?

I want the ID to be visible and the link to work even without the slug at the end. In case I ever change the slug in the database, any links would still work as the ID would be the only link to the article.

A clear, short example would be phenomenal.


Solution

  • The best way to do this is to have the second part of the url, the slug, be an irrelevant field in terms of how the lookup is done. Your route definition would be something like this:

    routes.MapRoute(
        "article"
        "articles/{id}/{slug}",
        new { controller = "Article", action = "Index", slug = "" }
    );
    

    And the matching action:

    public ActionResult Index(int id, string slug) {
        var article = _repository.GetById<Article>(id);
    
        ......
    
        return View();
    }
    

    If you're concerned about people requesting an invalid slug with a valid ID (and the impact this can have on SEO), then your controller action might have an additional operation which validates the slug against the article and does a 301 redirect to the desired URL whenever an incorrect slug is provided. This is what StackOverflow does, by the way. If you modify the title part of a question URL you will see that the site redirects you.