StackOverflow like URL Routing

后端 未结 3 1608
离开以前
离开以前 2020-12-14 22:35

Its my understanding that the questions in StackOverflow has the following format

http://stackoverflow.com/questions/{question-id}/{slug-made-from-question-t         


        
3条回答
  •  鱼传尺愫
    2020-12-14 23:17

    You can do this with Response.RedirectPermanent available since 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);
            }
        }
    }
    

    On an unrelated side note, would like to think Stack Overflow is not saving the slug at database. Its created dynamically from title using something like this. I just altered the title of my question and the slug changed. It will be un-necessary to store the slug in database as it is redundant to title.

提交回复
热议问题