创建类似于Stack Overflow的短固定链接“这个问题的短暂固定链接”

时间:2010-10-28 23:15:31

标签: asp.net-mvc url-routing permalinks response.redirect short-url

我想我可能已经明白这是如何运作的,但我想确定一下。

我正在为新的ASP.NET MVC应用程序定义路由。我想创建类似于Stack Overflow的这个问题的简短永久链接的短固定链接

  

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

Stack Overflow使用什么路由和控制器机制来实现这种固定链接行为?

讨论Stack Overflow问题路线的其他问题:

1 个答案:

答案 0 :(得分:1)

我相信Stack Overflow路由的设置类似于:

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

基于302 Found指向问题的当前位置:我假设PermaLink控制器的问题操作看起来像这样:

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