Alex Rivera | Logout

Adding ID and title to URL slugs in ASP.NET MVC

Asked 2011-05-19T07:46:16.357
32

How do you redirect a request in ASP.NET MVC to its correct canonical version if part of the URL is missing?

Using Stack Overflow as an example, the site adds the question title to the end of its routes, but uses the question ID in the route to actually find the question. If the title gets omitted you will be redirected to the correct URL.

For example, visiting the URL:

stackoverflow.com/questions/9033 

will redirect to

stackoverflow.com/questions/9033/hidden-features-of-c

How does this work?

Edit
Report

2 Answers

3

While I don't know any specifics of how StackOverflow manage it, here's an overview of how you could do it

  • Retrieve the question from the database using the ID
  • Convert the stored question title into a URL compatible slug
  • If the converted title slug does not match the slug passed in the URL then redirect using the converted title slug.

This ensures the URL is always the correct one and avoids possible embarrassing fake URLs

answered 2011-05-19T07:54:10.127
0

Here is an example of how they might do it, but I believe your asking how it can be done and this should work.

First stage is to set-up 2 routes in the Global.asax

routes.MapRoute("WithQuestion", "questions/{id}/{name}", new { controller = "Questions", action = "Question", id = "1" });
routes.MapRoute("WithoutQuestion", "questions/{id}", new { controller = "Questions", action = "WithoutQuestion", id="1"});

Now in our Questions controller,

    public ActionResult Question(int id)
    {
        //Load the question as we have the name appended.
        // We could actually do a little validation here as well
        return View();
    }

    public ActionResult WithoutQuestion(int id)
    {
        //Load the question object
        //Generate the full URL and redirect
        return Redirect(FullURL)
    }

This is a very basic example but shows how you could do it.

answered 2011-05-19T08:23:22.167

Your Answer