Question

I want to implement a StackOverflow type URL redirect over my website. For e.g.

When you enter https://stackoverflow.com/questions/11227809/ in the browser it automatically redirects you to https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array.

And even when you enter a scrap value in place of title such as https://stackoverflow.com/questions/11227809/askl;fl;aksf it will also redirect you to the right one based over the post number 11227809.

Which type of redirect is this? Thats a 301 i know but how can I achieve this using .Net MVC?

I have seen a non MVC solution here Here But need a MVC based one. Thankyou.


My Route:

routes.MapRoute("QuestionUrlDetermine", "{qId}/{questionTitle}", new { controller = "Home", action = "QuestionUrlDetermine", questionTitle = UrlParameter.Optional }, new { qId = @"^\d{1,3}$" });

Action:

public ActionResult QuestionUrlDetermine (int qId)
{
    …
        return new RedirectResult(string.Format("/{0}/{1}", qId, questionTitle));
}

No correct solution

OTHER TIPS

You can have the last parameter optional and afterwards check in the Action where you open the question, if it matches the title of the question. If they don't match you can simply return a RedirectResult or RedirectToRouteResult

This can be easily be done using RedirectResult:

public ActionResult Question(int id)
{
    string title = GetFromDatabaseUsingQuestionId(id);
    return new RedirectResult(string.Format("/question/{0}/{1}", id, title));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top