通过代码给IIS增加主机头

    技术2022-05-11  88

    看了一醉解千愁的修改IIS目录的Asp.Net版本之后,想到以前想过要通过代码给IIS增加主机头,却一直没去研究,今天趁着兴趣,决定把这个问题解决了。对于Blog网站,如果需要为用户提供二级域名支持,而Web程序不是运行默认站点中,就需要在用户注册时通过代码给IIS增加相应的主机头。这个问题是通过Google搜索到Append a host header by code in IIS解决的,经过测试,确认方法可行并对代码进行了一些改进后,考虑到这个内容会给一些朋友带来帮助,于是就写了这篇文章。代码如下:static void Main(string[] args){AddHostHeader(1, null, 80, 'test.cnblogs.com'); }

    static void AddHostHeader(int siteid,string ip, int port, string domain){DirectoryEntry site = new DirectoryEntry('IIS://localhost/W3SVC/'+siteid);PropertyValueCollection serverBindings = site.Properties['ServerBindings'];string headerStr = string.Format('{0}:{1}:{2}',ip,port,domain);if (!serverBindings.Contains(headerStr)){serverBindings.Add(headerStr);}site.CommitChanges();}在找到Append a host header by code in IIS之前,我通过下面的代码没找到'ServerBindings'属性,走了一些弯路。

    DirectoryEntry site = new DirectoryEntry('IIS://localhost/W3SVC/1/root');代码很简单,需要说明的是siteid,默认站点是1,对于非默认站点,通过查看站点日志文件名就可以知道。 


    最新回复(0)