【问题标题】:Add a IIS host header to website programmatically以编程方式将 IIS 主机标头添加到网站
【发布时间】:2023-03-28 12:15:02
【问题描述】:

我想设置一个管理页面 (ASP.NET/C#),可以将 IIS 主机标头添加到托管管理页面的网站。这可能吗?

我不想添加 http 标头 - 我想模仿手动进入 IIS 的操作,调出网站的属性,单击网站选项卡上的高级,然后在高级网站识别屏幕和一个新的“身份”,包含主机头值、IP 地址和 tcp 端口。

【问题讨论】:

  • 我也想知道如何执行此操作,以使用户能够将自己的域指向我的系统。

标签: c# asp.net iis hostheader


【解决方案1】:

这是Adding Another Identity To A Site Programmatically RSS上的论坛

另外,这里有一篇关于如何Append a host header by code in IIS的文章:

以下示例将主机标头添加到 IIS 中的网站。这涉及更改 ServerBindings 属性。没有可用于将新的服务器绑定附加到此属性的 Append 方法,因此需要做的是读取整个属性,然后将其与新数据一起再次添加回来。这是在下面的代码中完成的。 ServerBindings 属性的数据类型为 MULTISZ,字符串格式为 IP:Port:Hostname。

请注意,此示例代码不进行任何错误检查。重要的是,每个 ServerBindings 条目都是唯一的,而您 - 程序员 - 负责检查这一点(这意味着您需要遍历所有条目并检查即将添加的内容是否是唯一的)。

using System.DirectoryServices;
using System;
 
public class IISAdmin
{
    /// <summary>
    /// Adds a host header value to a specified website. WARNING: NO ERROR CHECKING IS PERFORMED IN THIS EXAMPLE. 
    /// YOU ARE RESPONSIBLE FOR THAT EVERY ENTRY IS UNIQUE
    /// </summary>
    /// <param name="hostHeader">The host header. Must be in the form IP:Port:Hostname </param>
    /// <param name="websiteID">The ID of the website the host header should be added to </param>
    public static void AddHostHeader(string hostHeader, string websiteID)
    {
        
        DirectoryEntry site = new DirectoryEntry("IIS://localhost/w3svc/" + websiteID );
        try
        {                        
            //Get everything currently in the serverbindings propery. 
            PropertyValueCollection serverBindings = site.Properties["ServerBindings"];
            
            //Add the new binding
            serverBindings.Add(hostHeader);
            
            //Create an object array and copy the content to this array
            Object [] newList = new Object[serverBindings.Count];
            serverBindings.CopyTo(newList, 0);
            
            //Write to metabase
            site.Properties["ServerBindings"].Value = newList;            
                        
            //Commit the changes
            site.CommitChanges();
                        
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        
    }
}
 
public class TestApp
{
    public static void Main(string[] args)
    {
        IISAdmin.AddHostHeader(":80:test.com", "1");
    }
}

但我不确定如何遍历标头值来进行上述错误检查。

【讨论】:

    猜你喜欢
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    相关资源
    最近更新 更多