![](/img/trans.png)
[英]ASP.NET Core 6.0+: How to get the current (case-sensitive) IIS Website Name?
[英]Get IIS site name from for an ASP.NET website
在我的 ASP.NET Web 應用程序中,我想查找它在 IIS 中創建時給出的名稱,這是服務器獨有的。 我對網站的域名不感興趣,但對 IIS 中為該網站提供的實際名稱不感興趣。
我需要能夠為 IIS6 和 7 可靠地做到這一點。
明確地說,我在談論 IIS 中的給定名稱,而不是域名,也不是虛擬目錄路徑。
System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName();
這是檢索站點 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"))
{
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.