【问题标题】:add a host header to a website on IIS 7 programmatically以编程方式将主机标头添加到 IIS 7 上的网站
【发布时间】:2012-03-03 17:11:00
【问题描述】:

我想通过 Web 应用程序(asp.net 4.0 / C#)将主机标头添加到在 IIS7 上运行的网站。互联网上有一些示例,但我想其中大多数在 iis7 上不起作用。 (注意:Web 应用程序托管在同一台服务器上,所以我想在更改 iis 配置时不会出现安全问题)

感谢任何帮助,谢谢

【问题讨论】:

标签: asp.net c#-4.0 iis-7 directoryservices hostheaders


【解决方案1】:

我找到了这个解决方案,它对我有用。这是一个带有几个参数的小功能,只需要在你的 iss 配置中找到你的网站的 id。之后你必须提供服务器的 ip 地址(iis )、端口号和主机名到函数中,它将使用您输入的参数添加主机头。例如

AddHostHeader(2, "127.0.0.1:81", 81, "newsHostHeader");

  static void AddHostHeader(int? websiteID, string ipAddress, int? port, string hostname)
    {
        using (var directoryEntry = new DirectoryEntry("IIS://localhost/w3svc/" + websiteID.ToString()))
        {
            var bindings = directoryEntry.Properties["ServerBindings"];
            var header = string.Format("{0}:{1}:{2}", ipAddress, port, hostname);
            if (bindings.Contains(header))
              throw new InvalidOperationException("Host Header already exists!");
            bindings.Add(header);
            directoryEntry.CommitChanges();
        }
    }

(注意:不要忘记添加到页面使用 System.DirectoryServices;使用 Microsoft.Web.Administration; )

【讨论】:

  • 在 Windows 8 IIS 7.5 System.Runtime.InteropServices.COMException 上抛出 System.DirectoryServices.DirectoryEntry.Bind 发生
  • 也许您需要检查一些凭据设置,听起来 IUSR 用户不允许在您的 IIS 中向网站添加标头。
【解决方案2】:

上面的解决方案对我来说不太适用于 IIS7.5。 我最终不得不这样做 http://www.iis.net/configreference/system.applicationhost/sites/site/bindings/binding

【讨论】:

    猜你喜欢
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多