2

我有一个 IIS7 Web 服务器,它运行大量站点,每个站点都有多个绑定。每个站点都使用主机标头和自己的 IP。

使用 C# 我需要将所有绑定的 IP 更改为 0.0.0.0,以便它们侦听所有 IP。

我当前的代码不会添加新绑定,而是清除旧绑定。任何想法我做错了什么?

我的代码:

using (ServerManager iisServerManager = new ServerManager())
        {
            foreach (Site site in iisServerManager.Sites)
            {
                List<Microsoft.Web.Administration.Binding> bindings = new List<Microsoft.Web.Administration.Binding>();

                foreach (Microsoft.Web.Administration.Binding binding in site.Bindings)
                {
                    String protocol = binding.Protocol;

                    String hostHeader = binding.Host;

                    String ipAddress = "0.0.0.0";

                    Int32 port = binding.EndPoint.Port;

                    String bind = ipAddress + ":" + port + ":" + hostHeader;

                    binding.BindingInformation = bind;

                    bindings.Add(binding);
                }

                //Clear existing site bindings
                site.Bindings.Clear();

                Int32 bindingCount = site.Bindings.Count();

                foreach (Microsoft.Web.Administration.Binding binding in bindings)
                {
                    site.Bindings.Add(binding);

                    bindingCount = site.Bindings.Count();
                }

                bindingCount = site.Bindings.Count();

                iisServerManager.CommitChanges();
            }
        }
4

1 回答 1

4

您无需删除然后重新添加相同的绑定。您可以就地修改它们,然后提交您的更改。此外,当您想监听所有 IP 地址时,您想使用 '*' 而不是 '0.0.0.0' 的 IP 地址。

这对我有用...

using (ServerManager iisServerManager = new ServerManager())
{
    foreach (Site site in iisServerManager.Sites)
    {
        foreach (Binding binding in site.Bindings)
        {
            string ipAddress = "*";
            int port = binding.EndPoint.Port;
            string hostHeader = binding.Host;

            binding.BindingInformation = string.Format("{0}:{1}:{2}", ipAddress, port, hostHeader);
        }

        iisServerManager.CommitChanges();
    }
}
于 2012-10-19T19:23:20.537 回答