問題描述
將用戶重定向到外部站點 (Redirecting user to external site)
我想通過一個簡單的錨標記將用戶重定向到我的 ASP.NET MVC 應用程序之外的外部站點。棘手的部分是,用戶可以自己輸入鏈接。
如果用戶在字段中輸入:www.google.com
(壞用戶),他將被重定向到http://www.example.com/頁/www.google.com
。這是完全可以理解的,他應該在他的鏈接前面使用 http://
...
如果我硬編碼 http://<它會按預期工作/code>在鏈接前面像這樣:
up and away!
但是如果用戶要輸入 http://www.google.com
(好用戶),瀏覽器會重定向到 http://http//www.google.com
這無處可去..
所以現在的問題是: 無論鏈接是否包含 http,是否有幫助程序或方法或路由到外部站點的東西: //
還是沒有?@Url.ExternalLink(model.Url)
之類的東西會很棒。我可以自己寫這個,但不需要重新發明輪子,對吧?所以如果有輪子,請提供輪子!在此先感謝!
檢查了一堆鏈接,但它們不能滿足我對可變用戶輸入的需求(永遠不要相信用戶!): will still be valid.
Add regex validator to a View where user types in url 方法 2:
You can easily extend UrlHelper with a method:
public static string ExternalLink(this UrlHelper helper, string uri)
{
if (uri.StartsWith("http://")) return uri;
return string.Format("http://{0}", uri);
}
Examples
@Url.ExternalLink("http://google.com")
@Url.ExternalLink("google.com")
(by Thomas Mulder、Andrei Mihalciuc、Sergii Zhevzhyk)
參考文件