Question

Like stackoverflow, you have domain/questions/{id}/{title}

It doesn't matter what you actually send as title, if it's not the actual title of the question, it automatically does a permanent redirect 302 I think to the canonical url.

This is all nice and great.

What I'm wondering is how they create the links on the question listing. Since having the question id is not enough to create the url.

Can be done automatically via routing?

Must implemement some kind of big dictionary?

You pass the title to all views that list the questions ? so you end up with something like: @Url.Action("Question", new {id = item.QuestionId, title = item.QuestionTitle.ToPrettyUrl()}); in your links.

I have to create a scenario similar to this and I'm kinda interested to know if there's any magic behind the scenes or solution I can't think about right now.

Was it helpful?

Solution 2

Stackoverflow uses an inhouse attribute routing code.

Something similar to what http://attributerouting.net/ Attribute Routing does.

Which will be also shipped in MVC 5.

OTHER TIPS

Yes, whenever you are rendering the link you'll need to specify the title just like you have it.

Of course, you could always create a helper method to create these links and just pass in the parameters to ensure you are always including the friendly title.

As for the redirect, StackOverflow does a 301 Permanent redirect, not a 302 Temporary.

My general approach to this would be as follow:

public ActionResult QuestionDetail(int id, string title)
{
   var question = service.GetQuestion(id);

   if(title != question.Title.ToPrettyUrl())
   {
     var redirUrl = string.Format("/question/{0}/{1}", id, question.Title.ToPrettyUrl());
     return RedirectPermanent(redirectUrl);
   }

  return View(question)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top