簡體   English   中英

從 ASP.NET 網站獲取 IIS 站點名稱

[英]Get IIS site name from for an ASP.NET website

在我的 ASP.NET Web 應用程序中,我想查找它在 IIS 中創建時給出的名稱,這是服務器獨有的。 我對網站的域名不感興趣,但對 IIS 中為該網站提供的實際名稱不感興趣。

我需要能夠為 IIS6 和 7 可靠地做到這一點。

明確地說,我在談論 IIS 中的給定名稱,而不是域名,也不是虛擬目錄路徑。

System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName();

正如@belugabob 和@CarlosAg 已經提到的,我寧願使用System.Web.Hosting.HostingEnvironment.SiteName而不是System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName()因為 IApplicationHost.GetSiteName 方法不打算直接調用! ( msdn )

所以你最好使用 HostingEnvironment.SiteName 屬性! ( msdn )

我認為這應該是關於文檔的正確答案;)

這是檢索站點 ID 的相關帖子

這里有一些可能對你有用的代碼:

using System.DirectoryServices;
using System;

public class IISAdmin
{
   public static void GetWebsiteID(string websiteName)
   {
      DirectoryEntry w3svc = new DirectoryEntry("IIS://localhost/w3svc");

     foreach(DirectoryEntry de in w3svc.Children)
     {
        if(de.SchemaClassName == "IIsWebServer" && de.Properties["ServerComment"][0].ToString() == websiteName)
        {
           Console.Write(de.Name);
        }

     }

  }
  public static void Main()
  {
     GetWebsiteID("Default Web Site");
  }

}

這是原始帖子的鏈接。

我不確定它是否可以在 IIS7 上運行,但是如果您為 IIS7 安裝了 IIS6 兼容性組件,它應該可以運行。

您正在尋找ServerManager ( Microsoft.Web.Administration ),它提供對 IIS 7.0 配置系統的讀寫訪問。

遍歷 Microsoft.Web.Administration.SiteCollection,使用站點對象獲取對您網站的引用並讀取 Name 屬性的值。

// Snippet        
using (ServerManager serverManager = new ServerManager()) { 

var sites = serverManager.Sites; 
foreach (Site site in sites) { 
         Console.WriteLine(site.Name); // This will return the WebSite name
}

您還可以使用 LINQ 查詢 ServerManager.Sites 集合(請參見下面的示例)

// Start all stopped WebSites using the power of Linq :)
var sites = (from site in serverManager.Sites 
            where site.State == ObjectState.Stopped 
            orderby site.Name 
            select site); 

        foreach (Site site in sites) { 
            site.Start(); 
        } 

注意:Microsoft.Web.Administration僅適用IIS7

對於 IIS6,您可以同時使用 ADSI 和 WMI 來執行此操作,但我建議您選擇比 ADSI 更快的 WMI。 如果使用 WMI,請查看WMI Code Creator 1.0 (免費/由 Microsoft 開發)。 它將為您生成代碼。

HTH

您可以使用以下代碼

private string WebsiteName()
{
    string websiteName = string.Empty;
    string AppPath = string.Empty;
    AppPath = Context.Request.ServerVariables["INSTANCE_META_PATH"];
    AppPath = AppPath.Replace("/LM/", "IIS://localhost/");
    DirectoryEntry root = new DirectoryEntry(AppPath);
    websiteName = (string)root.Properties["ServerComment"].Value;
    return websiteName;
}

連接到遠程服務器時,您需要先執行 ServerManager.OpenRemote("serverName") 。

基本上做這樣的事情

            using (ServerManager srvMgr = ServerManager.OpenRemote("serverName"))
            {

            }

看 msdn 幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM