StackOverflow就像URL Routing一样

nav*_*een 11 c# asp.net redirect http-status-code-301 url-redirection

我的理解是StackOverflow中的问题具有以下格式

http://stackoverflow.com/questions/{question-id}/{slug-made-from-question-title}
Run Code Online (Sandbox Code Playgroud)

所以基本上问题是使用question-id检索的.所以无论我给slug什么价值都是无关紧要的.

首先我想知道这种理解是否错误:)

我有一个URL

http://stackoverflow.com/questions/6291678/convert-input-string-to-a-clean-readable-and-browser-acceptable-route-data
Run Code Online (Sandbox Code Playgroud)

然后我像这样手动更换了slu ..

http://stackoverflow.com/questions/6291678/naveen
Run Code Online (Sandbox Code Playgroud)

但它变成了原来的slu .. Firebug向我展示了改变后的URL上的永久重定向301.如何实现此功能?

aKz*_*enT 8

您可以Response.RedirectPermanent使用ASP.NET 4.0以后的可用方法执行此操作:

http://msdn.microsoft.com/en-us/library/system.web.httpresponse.redirectpermanent.aspx

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        string id = RouteData.Values["id"].ToString();
        string passedSlug = RouteData.Values["name"].ToString();
        //get the original slug from database / dymanic method
        string originalSlug = GetSlugFromID(id);

        if(!originalSlug.Equals(passedSlug))
        {
            var url = String.Format("~/test/{0}/{1}", id, originalSlug);
            Response.RedirectPermanent(url, true);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在一个不相关的附注中,我们认为Stack Overflow没有将slug保存在数据库中.它是使用类似的东西从标题动态创建的.我只是改变了我的问题的标题,并且slug改变了.将slug存储在数据库中是没有必要的,因为它对标题来说是多余的.


Sal*_*n A 5

这是通过301重定向首选规范URL完成的.该脚本检查请求的URL以查看URL是否与URL的"首选"版本匹配.如果没有,它会向浏览器发送301重定向,并告诉它页面已永久移动到此位置.

这样做的原因是相当明显的:如果没有这个,你可以构造成千上万像URL的http://stackoverflow.com/questions/6291678/foo,http://stackoverflow.com/questions/6291678/bar,http://stackoverflow.com/questions/6291678/blah,都指向相同的内容.搜索引擎会因重复内容而惩罚您.

编辑

在ASP.Net应用程序中,您可以将浏览器提供的slug与存储在数据库中的slug进行比较.如果它们不匹配,请发送301重定向.您可能无法通过web.config或其他方式执行此操作,因为涉及的数据库.这是我前一段时间在我的博客上发布的示例代码(不确定它是否可行):

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim myId As Integer = 1234
    Dim mySlug As String = "preferred-slug"
    If Request.Url.AbsolutePath.Equals("/" & myId & "/" & mySlug) = False Then
        Response.Clear()
        Response.Status = "301 Moved Permanently"
        Response.AddHeader("Location", "http://" & Request.Url.Host & "/" & myId & "/" & mySlug & Request.Url.Query)
        Response.End()
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)

我假设你已经实现了某种形式的URL重写,它会/\d+/.+向你的asp.net页面抛出任何请求.