ahsteele
ahsteele

Reputation: 26514

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:

Upvotes: 5

Views: 1743

Answers (1)

ahsteele
ahsteele

Reputation: 26514

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 });
    }
}

Upvotes: 1

Related Questions