如何从IIS通过C#获取网站名称?

时间:2014-04-07 12:08:11

标签: c# web port servermanager

在IIS-Manager中,默认网站绑定在端口80上。如何使用c#按网站名称获取端口?我尝试了以下代码:

var lWebsite = "Default Web Site";
var lServerManager = new ServerManager();
var lPort = lServerManager.Sites[lWebsite].Bindings.GetAttributeValue("Port");

lPort导致null,并出现invalid index异常。但是赋值var lPort = lServerManager.Sites[lWebsite]可以工作。

1 个答案:

答案 0 :(得分:10)

当您访问Sites [lWebsite] .Bindings时,您正在访问绑定的集合。当你尝试调用GetAttributeValue(" Port")时,它会失败,因为这没有意义 - 集合本身没有与之关联的端口号,它只是一个集合

如果您想要访问每个绑定使用的端口号,您需要遍历这些绑定并询问每个绑定的相关端口号:

var site = lServerManager.Sites[lWebsite];
foreach (var binding in site.Bindings)
{
    int port = binding.EndPoint.Port;
    // Now you have this binding's port, and can do whatever you want with it.
}

值得强调的是,网站可以绑定到多个端口。你谈到了"""端口,但情况不一定 - 例如,通过HTTP和HTTPS提供服务的网站将有两个绑定,通常在端口80和443上。这就是为什么你&#39 ;必须处理绑定的集合,即使在您的情况下,集合可能只包含一个绑定,它仍然是一个集合。

有关详细信息,请查看the Binding class的MSDN文档。请注意,您可能感兴趣的某些内容将涉及访问绑定的EndPoint属性,如上例所示。