看了一醉解千愁的修改IIS目錄的asp.net版本之后,想到以前想過(guò)要通過(guò)代碼給IIS增加主機(jī)頭,卻一直沒去研究,今天趁著興趣,決定把這個(gè)問題解決了。
對(duì)于Blog網(wǎng)站,如果需要為用戶提供二級(jí)域名支持,而Web程序不是運(yùn)行默認(rèn)站點(diǎn)中,就需要在用戶注冊(cè)時(shí)通過(guò)代碼給IIS增加相應(yīng)的主機(jī)頭。
這個(gè)問題是通過(guò)Google搜索到Append a host header by code in IIS解決的,經(jīng)過(guò)測(cè)試,確認(rèn)方法可行并對(duì)代碼進(jìn)行了一些改進(jìn)后,考慮到這個(gè)內(nèi)容會(huì)給一些朋友帶來(lái)幫助,于是就寫了這篇文章。
代碼如下:
static void Main(string[] args)
{
AddHostHeader(1, null, 80, "test.VEVb.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之前,我通過(guò)下面的代碼沒找到"ServerBindings"屬性,走了一些彎路。
DirectoryEntry site = new DirectoryEntry("IIS://localhost/W3SVC/1/root");
代碼很簡(jiǎn)單,需要說(shuō)明的是siteid,默認(rèn)站點(diǎn)是1,對(duì)于非默認(rèn)站點(diǎn),通過(guò)查看站點(diǎn)日志文件名就可以知道。
出處:dudu-快樂程序員
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注