2012-11-07 48 views
28

我在其中有一個路徑的本地應用程序:HttpContext.Current.Request.Url.Host它返回什麼?

http://localhost:950/m/pages/Searchresults.aspx?search=knife&filter=kitchen 

但是當這種去集成環境或者是生產,這將是像

http://www.someshopping.com/m/pages/SearchResults.aspx?search=knife&filter=kitchen 

對於某些情況下,我需要只是通過:

www.someshopping.com 

我的XSLT文件,並在功能之一,我使用這個:

string currentURL = HttpContext.Current.Request.Url.Host; 

這會在本地環境中返回我「localhost」。將相同的代碼返回我:

www.someshopping.com生產(我不需要的http://

只是不想採取任何機會。所以問了這個愚蠢的問題。

+3

也許應該是'string host = HttpContext.Current.Request.Url.Host;' – Spike0xff

回答

38

是的,只要你的網址輸入到瀏覽器www.someshopping.com和你不使用URL重寫,然後

string currentURL = HttpContext.Current.Request.Url.Host; 

將返回www.someshopping.com

注意當地的區別調試環境和生產環境

+0

它返回'HOSTNAME'頭或本地地址,如果頭不存在。查看詳細信息:https://referencesource.microsoft.com/#System.Web/HttpRequest.cs,36cdd1ccad69cf75 – Alex

15

Host屬性將返回您在訪問網站時使用的域名。所以,在你的開發環境,因爲你的要求

http://localhost:950/m/pages/Searchresults.aspx?search=knife&filter=kitchen 

它返回localhost。您可以掰開你的網址,像這樣:

Protocol: http 
Host: localhost 
Port: 950 
PathAndQuery: /m/pages/SearchResults.aspx?search=knight&filter=kitchen 
+0

所以我的問題是,這將返回生產環境www.someshopping.com? :) –

+0

是的,假設您在製作中請求的URL是www.someshopping.com。 – Tejs

3

試試這個:

string callbackurl = Request.Url.Host != "localhost" 
    ? Request.Url.Host : Request.Url.Authority; 

這將爲本地以及生產環境中工作。因爲本地使用帶有端口號的url,這可能使用Url.Host。

+6

你應該總是使用'Request.IsLocal'來檢查它是否是本地請求,不需要比較'Request.Url.Host',因爲如果我真的寫了'http:// LocalHost/...' – balexandre

相關問題