且构网

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

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

更新时间:2022-11-06 13:10:43

如果您使用的是 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).

您将不得不使用互操作服务并执行与此类似的操作(此示例使用两个对象,服务器和站点,它们是存储服务器和站点配置的自定义类的实例):

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;

查看更多此处