2016-06-21 24 views
0

我正在編寫一個簡單的URL縮寫器。RedirectPermanent未重定向到網址

除重定向外,一切正常,

這是一種嘗試重定向代碼:

public async Task<ActionResult> Click(string segment) 
    { 
     string referer = Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : string.Empty; 
     Stat stat = await this._urlManager.Click(segment, referer, Request.UserHostAddress); 
     return this.RedirectPermanent(stat.ShortUrl.LongUrl); 
    } 

當我輸入的是縮短的鏈接,這樣http://localhost:41343/5d8a2a,它重定向我http://localhost:41343/www.google.com.br而不是www.google.com.br。

編輯

檢查答案後,它的工作原理。這是最後一段代碼。

if (!stat.ShortUrl.LongUrl.StartsWith("http://") && !stat.ShortUrl.LongUrl.StartsWith("https://")) 
      return this.RedirectPermanent("http://" + stat.ShortUrl.LongUrl); 
     else 
      return this.RedirectPermanent(stat.ShortUrl.LongUrl); 

謝謝!

+0

又是什麼'LongUrl'返回? –

+0

@DovydasSopa longUrl返回www.google.com –

+0

如果LongUrl包含http://,它將起作用。有沒有辦法引起它,而不是檢查網址是否包含http://? –

回答

3

而不是RedirectPermanent()嘗試使用Redirect()像下面一樣。指定的URL必須是絕對URL,否則它將嘗試在您的應用程序中重定向。

您可以檢查的http://存在並添加相應

if(!stat.ShortUrl.LongUrl.Contains("http://")) 
    return Redirect("http://" + stat.ShortUrl.LongUrl); 

(OR)

使用StartsWith()字符串函數

if(!stat.ShortUrl.LongUrl.StartsWith()("http://")) 
    return Redirect("http://" + stat.ShortUrl.LongUrl); 
+0

同樣的問題。如果它不是帶有http://的絕對url,它就不會工作。 –

+0

@BrunoXavier,如果有幫助,請參閱編輯答案。 – Rahul

+2

不包含'。使用'StartsWith'。 –