After reading the Asp.Net version of Yizui Jie Qianchou's article on modifying the IIS directory, I thought that I had thought about adding a host header to IIS through code before, but never studied it. Today, I took advantage of my interest and decided to solve this problem.
For blog websites, if you need to provide secondary domain name support for users, and the web program does not run in the default site, you need to add the corresponding host header to IIS through code when the user registers.
This problem was solved through Google search to Append a host header by code in IIS. After testing, it was confirmed that the method was feasible and some improvements were made to the code. Considering that this content would be helpful to some friends, I wrote this articles.
The code is as follows:
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();
}
Before finding Append a host header by code in IIS, I failed to find the "ServerBindings" attribute through the following code and took some detours.
DirectoryEntry site = new DirectoryEntry("IIS://localhost/W3SVC/1/root");
The code is very simple. What needs to be explained is the siteid. The default site is 1. For non-default sites, you can know it by looking at the site log file name.
Source: dudu-happy programmer