在 IIS-Manager 中,默认网站绑定(bind)在端口 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]
有效。
最佳答案
当您访问 Sites[lWebsite].Bindings 时,您正在访问绑定(bind)的集合。当您随后尝试调用 GetAttributeValue("Port") 时,它会失败,因为这毫无意义 - 集合本身没有与之关联的端口号,它只是一个集合。
如果您想访问每个绑定(bind)使用的端口号,您需要遍历这些绑定(bind)并向每个绑定(bind)询问其关联的端口号:
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.
}
值得强调的是,网站可以绑定(bind)到多个端口。您谈论的是获取“端口”,但情况不一定如此——例如,同时通过 HTTP 和 HTTPS 提供服务的网站将有两个绑定(bind),通常在端口 80 和 443 上。这就是为什么您必须处理集合 绑定(bind),即使在您的情况下该集合可能只包含一个绑定(bind),它仍然是一个集合。
有关更多详细信息,请查看 the Binding class 的 MSDN 文档.请注意,您可能感兴趣的一些内容将涉及访问绑定(bind)的 EndPoint 属性,如上例所示。
关于c# - 如何从 IIS 通过 C# 通过网站名称获取端口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22911993/