Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create short permalinks similar to Stack Overflow's "short permalink to this question"

I think I might already understand how this works, but wanted to be sure.

I am in the process of defining the routes for a new ASP.NET MVC application. I'd like to create short permalinks similar to Stack Overflow's short permalink to this question:

Create short permalinks similar to Stack Overflow's "short permalink to this question"

What route and controller mechanism is Stack Overflow using for this permalink behavior?

Other Questions discussing Stack Overflow question routes:

  • How can I create a friendly URL in ASP.NET MVC?
  • How do you include a webpage title as part of a webpage URL?
  • Creating search engine friendly URL's in ASP.NET MVC
like image 819
ahsteele Avatar asked Nov 15 '22 06:11

ahsteele


1 Answers

I believe that the Stack Overflow routes are setup something similar to this:

routes.MapRoute("question-permalink", "q/{questionId}/{userId}", 
    new { controller = "PermaLinkController",
        action = "Question", userId = UrlParameter.Optional },
    new { questionId = "[0-9]+", userId = "[0-9]+" });

Based on the 302 Found pointing to the question's current location: I assume the PermaLink controller's Question action looks something like this:

public class PermaLinkController : Controller
{
    public Question (int questionId, int? userId)
    {
        // do work to record userId that shared link
        // ...
        // now redirect
        Response.RedirectToRoute("question", new { questionId = questionId });
    }
}
like image 133
ahsteele Avatar answered Dec 05 '22 00:12

ahsteele