且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用C#以编程方式在IIS中创建网站并设置端口号

更新时间:2022-11-06 13:01:46

如果您使用的是IIS 7,则会有一个名为 Microsoft.Web.Administration

If you're using IIS 7, there is a new managed API called Microsoft.Web.Administration

以上博文中的一个例子:

An example from the above blog post:

ServerManager iisManager = new ServerManager();
iisManager.Sites.Add("NewSite", "http", "*:8080:", "d:\\MySite");
iisManager.CommitChanges(); 

如果您正在使用IIS 6并希望这样做,那么遗憾的是它更复杂。

If you're using IIS 6 and want to do this, it's more complex unfortunately.

您必须在每台服务器上创建一个Web服务,这是一个处理网站创建的Web服务,因为通过网络的直接用户模拟将无法正常工作(如果我没记错了。)

You will have to create a web service on every server, a web service that handles the creation of a website because direct user impersonation over the network won't work properly (If I recall this correctly).

你将不得不使用Interop Services并做类似的事情(这个例子使用两个对象,服务器和站点,它们是实例存储服务器和站点配置的自定义类:

You will have to use Interop Services and do something similar to this (This example uses two objects, server and site, which are instances of custom classes that store a server's and site's configuration):

string metabasePath = "IIS://" + server.ComputerName + "/W3SVC";
DirectoryEntry w3svc = new DirectoryEntry(metabasePath, server.Username, server.Password);

string serverBindings = ":80:" + site.HostName;
string homeDirectory = server.WWWRootPath + "\\" + site.FolderName;


object[] newSite = new object[] { site.Name, new object[] { serverBindings }, homeDirectory };

object websiteId = (object)w3svc.Invoke("CreateNewSite", newSite);

// Returns the Website ID from the Metabase
int id = (int)websiteId;

查看更多这里