Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

c# - StackOverflow like URL Routing

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

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

So basically the question is retrieved using the question-id. so whatever value I give the slug is immaterial.

First I would like to know whether this understanding is wrong :)

I have a URL

http://stackoverflow.com/questions/6291678/convert-input-string-to-a-clean-readable-and-browser-acceptable-route-data

Then I changed the slug manually like this.

http://stackoverflow.com/questions/6291678/naveen

But it changed to the original slug. Firebug showed me a permenant redirect 301 on the altered URL. How to implement this functionality?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...