2010-03-01 43 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