在C#中更改IIS7绑定的IP

时间:2012-10-19 14:30:18

标签: c# iis-7

我有一个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();
            }
        }

1 个答案:

答案 0 :(得分:3)

您不需要删除然后重新添加相同的绑定。您可以在适当的位置修改它们,然后提交更改。此外,您想使用&#39; *&#39;的IP地址。而不是&#39; 0.0.0.0&#39;当你想听所有的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();
    }
}