2010-03-01 28 views
1

在線程中運行時,是否可以獲取當前Web應用程序的基本URI?來自後臺進程的基本Uri

請記住HttpContext.Current將爲空,因此沒有Request對象可供使用。

目標:能夠從線程向Web應用程序中的不同URL發出Web請求以獲取呈現的輸出。

回答

1

有這樣做的幾種方法:

  1. 假設你是好使用本地主機的域名,使用 "http://localhost" + HttpRuntime.AppDomainAppVirtualPath
  2. 如果您需要確切的域名,並確定該應用程序使用https和所有那些花哨的東西,你需要訪問HttpRequest本身。在這種情況下,在創建線程本身的方法中創建基礎url,並將其作爲參數傳遞給線程。
 
    string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority 
         + Request.ApplicationPath.TrimEnd('/') + "/"; 
    ParameterizedThreadStart worker= new ParameterizedThreadStart(MyWorkerMethod); 
    new Thread(worker).Start(baseUrl); 
+0

肯定希望能得到全URL(域和協議)。雖然 – Rob 2010-03-02 00:00:49

0

你可以得到域和協議部分從IIS ADSI提供者,但由於可以有許多綁定,你必須選擇一個自己:

protected void ListServerBindings() 
{ 
    var ls = new List<string>(); 
    var ss = HttpRuntime.AppDomainAppId.Split('/'); 
    var e = new DirectoryEntry("IIS://localhost/" + ss[2] + "/" + ss[3]); 
    foreach(string s in e.Properties["ServerBindings"]) 
    { 
     ss = s.Split(':'); 
     ls.Add("http://" + (ss[2].Length == 0 ? "localhost" : ss[2]) + (ss[1] == "80" ? null : ":" + ss[1]) + HttpRuntime.AppDomainAppVirtualPath); 
    } 
    foreach(string s in e.Properties["SecureBindings"]) 
    { 
     ss = s.Split(':'); 
     ls.Add("https://" + (ss[2].Length == 0 ? "localhost" : ss[2]) + (ss[1] == "443" ? null : ":" + ss[1]) + HttpRuntime.AppDomainAppVirtualPath); 
    } 
    Response.Write(string.Join("<br />", ls.ToArray())); 
} 
+0

從調試器:AppDomainAppId =「259be8bd」 – Rob 2010-03-02 01:43:03

+0

這顯然只適用於IIS,而不是在Visual Studio內置的Web服務器。 – 2010-03-02 04:12:51

+0

D'OH!假裝這次談話從未發生過 – Rob 2010-03-02 04:29:41