2014-03-03 32 views
0

我想實現一個StackOverflow類型的URL重定向通過我的網站。 例如實現StackOverflow類型的URL重定向

當您在瀏覽器中輸入https://stackoverflow.com/questions/11227809/時,它會自動將您重定向到https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array

即使您輸入廢品價值代替標題,例如https://stackoverflow.com/questions/11227809/askl;fl;aksf,它也會將您重定向到正確的郵政編號11227809

這是哪種類型的重定向?那是一個301我知道,但我怎麼能實現這一點使用.Net MVC?

我在這裏看到過一個非MVC解決方案Here但是需要一個基於MVC的解決方案。 Thankyou。


My Route:

routes.MapRoute("QuestionUrlDetermine", "{qId}/{questionTitle}", new { controller = "Home", action = "QuestionUrlDetermine", questionTitle = UrlParameter.Optional }, new { qId = @"^\d{1,3}$" }); 

Action:

public ActionResult QuestionUrlDetermine (int qId) 
{ 
    … 
     return new RedirectResult(string.Format("/{0}/{1}", qId, questionTitle)); 
} 
+0

我無法找到原來的答案,但這是相似的: http://stackoverflow.com/questions/18784979/mvc-routing-changing-routes –

+0

我已更新我的問題與代碼請檢查。 – Maven

+0

類似的帖子:http://stackoverflow.com/questions/16248732/mvc-4-creating-slug-type-url – shakib

回答

1

你可以有最後一個參數可選的,在你打開的問題,如果這個問題的稱號相匹配的行動事後檢查。如果它們不匹配,你可以簡單地返回一個RedirectResultRedirectToRouteResult

+0

這說'404'當路由沒有被定義,當我定義路由它進入重定向循環,因爲在RedirectResult之後,它會針對路線再次擊中動作。我已經用代碼更新了我的問題,請檢查。 – Maven

+0

你用'public ActionResult QuestionUrlDetermine(int qId,string questionTitle)'定義了另一個函數嗎?在沒有'RedirectResult'的情況下,應該解決這個問題 – peter

1

這可以很容易地使用RedirectResult來完成:

public ActionResult Question(int id) 
{ 
    string title = GetFromDatabaseUsingQuestionId(id); 
    return new RedirectResult(string.Format("/question/{0}/{1}", id, title)); 
} 
+0

這就是'404',當路由沒有被定義,並且當我定義它進入重定向循環的路由時,因爲在'RedirectResult'之後,它觸發並且再次返回路由。 – Maven