使用ASP.NET操作IIS7中使用应用程序

在最新发布的启明星Portal里,增加了安装程序,下面说一下.NET对IIS7操作。IIS7的操作和IIS5/6有很大的不同,在IIS7里增加了 Microsoft.Web.Administration 命名空间里,增加了ServerManager、Site几个大类来操作IIS7。

下面是一些核心代码,可以直接使用

1)建立虚拟目录

建立虚拟目录时,默认使用“Default Web Site”,也就是默认建立在Default Web Site, CreateVdir需要两个参数:虚拟路径名称和实际的物理路径

public static bool CreateVdir(string vdir, string phydir)

{

ServerManager serverManager = new ServerManager();

Site mySite = serverManager.Sites["Default Web Site"];

mySite.Applications.Add("/" + vdir, phydir);

serverManager.CommitChanges();

return true;

}

这里建立的是在Default Web Site下的虚拟目录,将上面的mysite修改为

Site mySite = iisManager.Sites.Add("test", "http", "*:80:" + WebName + ".intranet." + TLD, @"c:\Webs\" + WebName);

则可以建立网站。这2个区别是:你建立一个网站。前面的访问示意URL是 http://www.dotnetcms.org/book ,而后者是http://book.dotnetcms.org

接下来创建应用程序池

public static void CreateAppPool( string appPoolName)

{

try

{

ServerManager serverManager = new ServerManager();

serverManager.ApplicationPools.Add(appPoolName);

ApplicationPool apppool = serverManager.ApplicationPools[appPoolName];

apppool.ManagedPipelineMode = ManagedPipelineMode.Classic;

serverManager.CommitChanges();

apppool.Recycle();

}

catch

{ }

}

这里ManagedPipelineMode的取值 ManagedPipelineMode.Classic;IIS7支持经典Classic方式和Interget集成方式,在集成方式下

自定义的handler和Module可能无效,如果你想和以前IIS5/6版本兼容可以使用Classic方式,否则建议使用集成方式。

下面代码演示了如何把虚拟目录分配到应用程序池,和IIS5/6最大的区别是vdir其实是vdir path,所以这里加了一个“/”,表示一个虚路径。

public static void AssignVDirToAppPool(string vdir, string appPoolName)

{

try

{

ServerManager serverManager = new ServerManager();

Site site = serverManager.Sites["Default Web Site"];

site.Applications["/" + vdir].ApplicationPoolName = appPoolName;

serverManager.CommitChanges();

}

catch

{

}

}

最后增加一个删除操作

public static bool DeleteVdir(string vDirName)

{

try

{

ServerManager serverManager = new ServerManager();

Site mySite = serverManager.Sites["Default Web Site"];

Microsoft.Web.Administration.Application application = mySite.Applications["/" + vDirName];

mySite.Applications.Remove(application);

serverManager.CommitChanges();

return true;

}

catch

{

return false;

}

}

到此,.NET操作IIS7的基本功能已经实现了。