用VS2005制作网页对IIS进行操作

主要是想用一下VS2005,对IIS的操作在IIS Admin中本来就可以进行管理。所以将就看,无所谓有用无用哈。^_^
在网上也找了一下,参考了一些别人的写法,如果有什么不对的,请你多指点。
本文只写出了部分代码,其他的内容请你自己补足。
环境:Windows2003 + VS2005

先需要添加两个引用: System.DirectoryServicesSystem.Management
添加虚拟目录:
做了一个简单的页面,如下图:


这里只是为了说明很多IIS里面站点的属性可以设置(具体属性及说明见本文最后),在本例子的aspx.cs文件里面,并不一定使用了页面控件的值;还有就是在程序中只是为了实现,并未对程序的写法进行严格的要求。


处理添加按钮的点击事件:
public static string VirDirSchemaName = "IIsWebVirtualDir";

IISManager iis = new IISManager();
iis.Connect();
iis.DefaultPage = DefaultPage.Text.Trim();
ReturnMessage.Text = iis.CreateVirtualDirectory(VirtualPath.Text.Trim(), PhysicalPath.Text.Trim());

在本文中,操作IIS的方法全部写在自定义的类IISManger中。上面的CreateVirtualDirectory()如下:
#region CreateVirtualDirectory 添加虚拟目录

public string CreateVirtualDirectory(string nameDirectory, string realPath)


{


DirectoryEntry folderRoot = _iisServer.Children.Find("Root", VirDirSchemaName);


try


{


DirectoryEntry newVirDir = folderRoot.Children.Add(nameDirectory, VirDirSchemaName);



newVirDir.Properties["Path"].Insert(0, realPath);
//
虚拟目录的绝对路径

newVirDir.Properties["AccessExecute"][0] = false;
//
可执行文件。执行权限下拉菜单中

newVirDir.Properties["AccessRead"][0] = true;
//
读取

newVirDir.Properties["AccessWrite"][0] = true;
//
写入


newVirDir.Properties["ContentIndexed"][0] = true;
//
资源索引

newVirDir.Properties["DefaultDoc"][0] = DefaultPage;
//
默认页面

newVirDir.Properties["AppFriendlyName"][0] = "world";
//
友好的显示名称

newVirDir.Properties["AppIsolated"][0] = 2;
//
0 表示应用程序在进程内运行,值 1 表示进程外,值 2 表示进程池

newVirDir.Properties["AccessScript"][0] = true;
//
可执行脚本。执行权限下拉菜单中
            

newVirDir.Properties["DontLog"][0] = true;



newVirDir.Invoke("AppCreate", true);


newVirDir.CommitChanges();


folderRoot.CommitChanges();


_iisServer.CommitChanges();


return "Add success";


}


catch (Exception e)


{


return "Sorry!Error when adding the virtual path. Return message is : " + e.Message;


}



}

#endregion

处理添加按钮的点击事件:
public static string VirDirSchemaName = "IIsWebVirtualDir";

IISManager iis = new IISManager();
iis.Connect();
iis.DefaultPage = DefaultPage.Text.Trim();
ReturnMessage.Text = iis.CreateVirtualDirectory(VirtualPath.Text.Trim(), PhysicalPath.Text.Trim());

在本文中,操作IIS的方法全部写在自定义的类IISManger中。上面的CreateVirtualDirectory()如下:
#region CreateVirtualDirectory 添加虚拟目录

public string CreateVirtualDirectory(string nameDirectory, string realPath)


{


DirectoryEntry folderRoot = _iisServer.Children.Find("Root", VirDirSchemaName);


try


{


DirectoryEntry newVirDir = folderRoot.Children.Add(nameDirectory, VirDirSchemaName);



newVirDir.Properties["Path"].Insert(0, realPath);
//
虚拟目录的绝对路径

newVirDir.Properties["AccessExecute"][0] = false;
//
可执行文件。执行权限下拉菜单中

newVirDir.Properties["AccessRead"][0] = true;
//
读取

newVirDir.Properties["AccessWrite"][0] = true;
//
写入


newVirDir.Properties["ContentIndexed"][0] = true;
//
资源索引

newVirDir.Properties["DefaultDoc"][0] = DefaultPage;
//
默认页面

newVirDir.Properties["AppFriendlyName"][0] = "world";
//
友好的显示名称

newVirDir.Properties["AppIsolated"][0] = 2;
//
0 表示应用程序在进程内运行,值 1 表示进程外,值 2 表示进程池

newVirDir.Properties["AccessScript"][0] = true;
//
可执行脚本。执行权限下拉菜单中
            

newVirDir.Properties["DontLog"][0] = true;



newVirDir.Invoke("AppCreate", true);


newVirDir.CommitChanges();


folderRoot.CommitChanges();


_iisServer.CommitChanges();


return "Add success";


}


catch (Exception e)


{


return "Sorry!Error when adding the virtual path. Return message is : " + e.Message;


}



}

#endregion

开始的时候,不管怎么样调试上面的代码,始终报错。在网上查了一下资料,才发现是权限不够。结果我是在组件管理器里面修改,然后又在文件夹修改,改来改去始终没找到关键改哪里,差点累死俺。最后才找到别人曾经做过的方法,在web.config文件里面下添加一个,我把里面的信息改成了administrator,然后就成功了。也有人说修改machine.config也可以,不过我没试。对于这种修改config文件的做法,我觉得不是最好的,应该是修改其他某个地方的权限就可以,把密码暴露出来始终不是什么好事,在MSDN上也没找到,如果哪位大哥知道,透露一下好了~~~~~~~~~~~~

连接IIS服务器的方法如下,操作IIS(添加,修改,删除)的时候都需要用到:
#region Connect 连接IIS服务器

public bool Connect()


{



if (_serverName == null)



return false;


try


{


_iisServer = new DirectoryEntry("IIS://" + _serverName + "/W3SVC/1");


_target = _serverName;


_connection = new ConnectionOptions();


_scope = new ManagementScope(@"//" + _serverName + @"/root/MicrosoftIISV2", _connection);


_scope.Connect();


}


catch


{


return false;


}


return IsConnected();


}



public bool IsConnected()


{


if (_target == null || _connection == null || _scope == null) return false;


return _scope.IsConnected;


}


#endregion



关于添加IIS虚拟目录,还可以参考:System.EnterpriseServices.Internal.IISVirtualRoot.Create()System.EnterpriseServices.Internal. Publish.CreateVirtualRoot()System.EnterpriseServices.Internal .SoapServerVRoot.CreateVirtualRootEx

删除虚拟目录:

#region DeleteVirtualDirectory 删除虚拟目录

public string DeleteVirtualDirectory(string nameDirectory)

{

DirectoryEntry folderRoot = _iisServer.Children.Find("Root", VirDirSchemaName);

DirectoryEntry newVirDir;

try

{

newVirDir = folderRoot.Children.Find(nameDirectory, VirDirSchemaName);

}

catch

{

return "Sorry! The virtual path does not exists!!";


}


try

{

folderRoot.Children.Remove(newVirDir);

folderRoot.CommitChanges();

_iisServer.CommitChanges();

return "Delete success";

}

catch (Exception e)

{


return "Sorry!Error when deleting the virtual path. Return message is :" + e.Message;

}


}
#endregion

同理,你也可以通过IIsWebVirtualDir对虚拟目录的属性进行修改。参考IIS帮助文件。

添加网站

页面如图:



开始的时候,以为可以原理和添加虚拟目录一样,直接操作就行了,在网上也找到一个方法,代码如下:

#region CreateWebSite2 创建网站的第二种方法

public string CreateWebSite2(string name, string path, string description,string serverID, string port, bool makeActive, string UserName, string Password)

{

try

{

DirectoryEntry iisObject = new DirectoryEntry("IIS://localhost/w3svc");

DirectoryEntry webSite = (DirectoryEntry)iisObject.Invoke("Create", new object[] { "IIsWebServer", serverID });

webSite.Properties["ServerComment"][0] = name;

webSite.Properties["ServerAutoStart"][0] = makeActive;

string prt = ":" + port.ToString() + ":";

webSite.Properties["ServerBindings"].Add(prt);

webSite.CommitChanges();


// Create new IIS virtual directory

DirectoryEntry virtualDirectory = (DirectoryEntry)webSite.Invoke("Create", new object[] { "IIsWebVirtualDir", "Root" });

virtualDirectory.CommitChanges();


// Set common properties

if (UserName != null)

{

virtualDirectory.Properties["AnonymousUserName"][0] = UserName;

virtualDirectory.Properties["AnonymousUserPass"][0] = Password;

}

virtualDirectory.Properties["AccessExecute"][0] = true;

virtualDirectory.Properties["EnableDefaultDoc"][0] = true;

virtualDirectory.Properties["DefaultDoc"][0] = "default.aspx";

Directory.Exists(path);

virtualDirectory.Properties["Path"][0] = path;

virtualDirectory.CommitChanges();



// set medium (pooled) application protection

virtualDirectory.Invoke("AppCreate2", new object[] { 2 });


// Commit the property/children changes to the virtual directory

virtualDirectory.Properties["AppFriendlyName"][0] = name;

virtualDirectory.CommitChanges();


if (makeActive)

{

try

{

webSite.Invoke("Start", new object[] { });

}

catch(Exception startException)

{

return "Create the site successfully! /r/nError when starting the site.Return message is :" + startException.Message;

}

}

return "Create the site successfully!";


}

catch(Exception createException)

{

return "Error when creating the site.Return message is :" + createException.Message;

}

}
#endregion


在页面中使用的时候始终不成功,查了一下IIS的帮助,也没有找到IIsWebServerCreate方法,不知道是不是IIS6中已经没有这个方法了。经过在网上仔细地查找和浏览IIS的帮助,终于还是找到一个通过调用WMI添加网站的办法,真是不容易啊!汗~~~~~~
代码:
#region CreateWebsite 添加网站

public string CreateWebSite(string serverID, string serverComment, string defaultVrootPath, string HostName, string IP, string Port)

{

try


{

ManagementObject oW3SVC = new ManagementObject (_scope, new ManagementPath(@"IIsWebService='W3SVC'"), null);



if (IsWebSiteExists (serverID))

{

return "Site Already Exists...";


}


ManagementBaseObject inputParameters = oW3SVC.GetMethodParameters ("CreateNewSite");

ManagementBaseObject[] serverBinding = new ManagementBaseObject[1];

serverBinding[0] = CreateServerBinding(HostName, IP, Port);

inputParameters["ServerComment"] = serverComment;

inputParameters["ServerBindings"] = serverBinding;

inputParameters["PathOfRootVirtualDir"] = defaultVrootPath;

inputParameters["ServerId"] = serverID;



ManagementBaseObject outParameter = null;

outParameter = oW3SVC.InvokeMethod("CreateNewSite", inputParameters, null);


// 启动网站

string serverName = "W3SVC/" + serverID;

ManagementObject webSite = new ManagementObject(_scope, new ManagementPath(@"IIsWebServer='" + serverName + "'"), null);

webSite.InvokeMethod("Start", null);


return (string)outParameter.Properties["ReturnValue"].Value;

}

catch (Exception ex)

{

return ex.Message;

}

}


public ManagementObject CreateServerBinding(string HostName, string IP, string Port)

{

try

{

ManagementClass classBinding = new ManagementClass(_scope, new ManagementPath("ServerBinding"), null);

ManagementObject serverBinding = classBinding.CreateInstance();

serverBinding.Properties["Hostname"].Value = HostName;

serverBinding.Properties["IP"].Value = IP;

serverBinding.Properties["Port"].Value = Port;

serverBinding.Put();

return serverBinding;

}

catch

{

return null;

}

}

#endregion

页面:
// 添加网站

protected void AddWebsite_Click(object sender, EventArgs e)

{

IISManager iis = new IISManager();

iis.Connect();


string serverID = "5556";

string serverComment = "Create Website";

string defaultVrootPath = @"D:/web";

string HostName = "World";

string IP = "";

string Port = "9898";


ReturnMessage.Text = iis.CreateWebSite(serverID,serverComment,defaultVrootPath,HostName,IP,Port);

}

删除网站的代码:
#region DeleteSite 删除站点

public string DeleteSite(string serverID)

{

try

{

string serverName = "W3SVC/" + serverID;

ManagementObject webSite = new ManagementObject(_scope, new ManagementPath(@"IIsWebServer='" + serverName + "'"), null);


webSite.InvokeMethod("Stop", null);

webSite.Delete();

webSite = null;


return "Delete the site succesfully!";

}

catch(Exception deleteEx)

{

return deleteEx.Message;


}

}

#endregion

同样的方式,也可以对网站对属性进行修改。


在使用WinForm的时候,同样可以根据这种方式对IIS进行操作。而且,里面涉及到权限的地方,更好操作,不像WebForm,默认的访问用户是NetWork Service,对本机的很多操作都需要明确的制定权限。你可以试一试。

通过本例,可以看到,完全可以自己编写代码对IIS进行需要对操作。需要注意的是:权限问题。如果想要了解更多的信息,请查阅IIS帮助文件及MSDN
PSMSDN好像有不少的bug哦,很多都还是E文的,而且例子也少,吼吼,要加紧学习E文啦…………………….

附:IIS的站点属性(详细内容,请查阅IIS帮助)
Read only properties of W3SVC/1/Root:
//
只读属性
AppIsolated = 2
属性指出应用程序是在进程内、进程外还是在进程池中运行。值 0 表示应用程序在进程内运行,值 1 表示进程外,值 2 表示进程池。
AppPackageID =
为事务提供 COM+ 应用程序标识符 (ID)。此 ID 在由组件服务管理的所有事务中使用。
AppPackageName =
为事务提供 COM+ 应用程序名。
AppRoot = /LM/W3SVC/1/ROOT
包含到应用程序根目录的配置数据库路径。
Caption =
提供对象的一段简短文本描述(一行字符串)。
Description =
提供对象的一段较长文本描述。
InstallDate =
表示安装对象的时间。缺少值并不表示对象没有安装。
Name = W3SVC/1/ROOT
定义了用来识别对象的标签。创建子类时,可以将 Name 属性改写为 Key 属性。
Status =
表示对象当前状态。各种可操作的和不可操作的状态都可以被定义。可操作的状态为“正常”、“已降级”和“预见故障”。“预见故障”表示一个组件可能运行正常但预计很快会出现故障。例如,启用 SMART 的硬盘。还可指定不可操作的状态。这些状态为“错误”、“启动”、“停止”和“服务”。后者(即“服务”)可用于磁盘镜像过程、重新加载用户权限列表或其他管理作业。并不是所有这类作业都联机;所以,被管理的组件不是“正常”状态或处于任何其他状态。

Read/Write properties of W3SVC/1/Root:
//
可读/可写
AccessExecute = False
true 表示不论文件类型是什么,文件或文件夹的内容都可以执行。
AccessFlags = 513
包含有用于配置文件访问权限的标志
AccessNoPhysicalDir = False
AccessNoRemoteExecute = False
true 表示拒绝远程请求执行应用程序;如果将 AccessExecute 属性设置为 true,只有来自 IIS 服务器所在的相同计算机的请求才会成功。您不能将 AccessNoRemoteExecute 设置为 false 来启用远程请求,或将 AccessExecute 设置为 false 来禁止本地请求。
AccessNoRemoteRead = False
true 表示拒绝远程请求查看文件;如果将 AccessRead 属性设置为 true,只有来自 IIS 服务器所在的相同计算机的请求才会成功。您不能将 AccessNoRemoteRead 设置为 false 来启用远程请求,或将 AccessRead 设置为 false 来禁止本地请求。
AccessNoRemoteScript = False
true 表示拒绝远程请求查看动态内容;如果将 AccessScript 属性设置为 true,只有来自 IIS 服务器所在的相同计算机的请求才会成功。您不能将 AccessNoRemoteScript 设置为 false 来启用远程请求,或将 AccessScript 设置为 false 来禁止本地请求。
AccessNoRemoteWrite = False
true 表示拒绝远程请求创建或更改文件;如果将 AccessWrite 属性设置为 true,只有来自 IIS 服务器所在的相同计算机的请求才会成功。您不能将 AccessNoRemoteWrite 设置为 false 来启用远程请求,或将 AccessWrite 设置为 false 来禁止本地请求。
AccessRead = True
true 表示可通过 Microsoft Internet Explorer 读取文件或文件夹的内容。
AccessScript = True
true 表示如果是脚本文件或静态内容,则可以执行文件或文件夹的内容。值 false 只允许提供静态文件,如 HTML 文件。
AccessSource = False
true 表示如果设置了读取或写入权限,则允许用户访问源代码。源代码包括 Microsoft® Active Server Pages (ASP) 应用程序中的脚本。
AccessSSL = False
true 表示文件访问需要带有或不带有客户端证书的 SSL 文件权限处理。
AccessSSL128 = False
true 表示文件访问需要至少 128 位密钥、带有或不带有客户端证书的 SSL 文件权限处理。
AccessSSLFlags = 0
默认值 0 表示未设置任何 SSL 权限。
AccessSSLMapCert = False
true 表示 SSL 文件权限处理将客户端证书映射到 Microsoft Windows® 操作系统的用户帐户上。要实现映射,必须将 AccessSSLNegotiateCert 属性设置成 true
AccessSSLNegotiateCert = False
true 表示 SSL 文件访问处理从客户端请求证书。值 false 表示如果客户端没有证书,仍可继续访问。如果服务器请求证书但证书不可用(即使也将 AccessSSLRequireCert 设成 true),某些版本的 Internet Explorer 将关闭连接。
AccessSSLRequireCert = False
true 表示 SSL 文件访问处理从客户端请求证书。如果客户端没有提供证书,连接会关闭。当使用 AccessSSLRequireCert 时,必须将 AccessSSLNegotiateCert 设成 true
AccessWrite = False
true 表示允许用户将文件及其相关属性上载到服务器上已启用的目录中,或者更改可写文件的内容。只有使用支持 HTTP 1.1 协议标准的 PUT 功能的浏览器,才能执行写入操作。
AdminACLBin =
Microsoft® Exchange Server 使用
AnonymousPasswordSync = True
指出 IIS 是否应该为试图访问资源的匿名用户处理用户密码。下表列出了该属性行为的详细说明:如果将 AnonymousPasswordSync 设置为 false,管理员必须手动设置匿名用户密码的 AnonymousUserPass 属性;否则匿名访问将无法正常工作。 如果将 AnonymousPasswordSync 设置为 true,将由 IIS 设置匿名用户密码。 如果将 AnonymousPasswordSync 设置为 true 并且配置数据库属性 AllowAnonymous 值为 false,则不允许任何用户登录到 FTP 服务器。
AnonymousUserName = IUSR_COMPUTERNAME
指定用来验证匿名用户的已注册的本地用户名。服务器将每个服务器操作与用户名和密码关联起来。
AnonymousUserPass = XXXXXXXXXXXX
指定用来验证匿名用户的已注册的本地用户密码。服务器将每个服务器操作与用户名和密码关联起来。
AppAllowClientDebug = False
指定是否允许客户端调试。该属性与应用于服务器端调试的 AppAllowDebugging 无关。
AppAllowDebugging = False
指定是否允许在服务器上进行 ASP 调试。该属性与应用于客户端调试的 AppAllowClientDebug 属性无关。
AppFriendlyName = 默认应用程序     软件包或应用程序的用户好记名称
AppOopRecoverLimit = -1
进程外应用程序在出现故障后重新启动的最大次数。服务器不会响应超出该范围的组件请求。该属性不适用于进程内运行的应用程序或扩展。
AppPoolId = ASP.NET V2.0
应用程序在其中路由的应用程序池
AppWamClsid =
为应用程序的 Web 应用程序管理 (WAM) 接口提供类 ID
AspAllowOutOfProcComponents = True
IIS 4.0 中,AspAllowOutOfProcComponents 属性指定是否允许 ASP 脚本调用进程外组件,这些组件是在应用程序内启动的可执行程序。在 IIS 5.0 中,该属性已过时,并且属性值将被忽略。但是,使用该属性的脚本仍然可以正常运行。
AspAllowSessionState = True
启用 ASP 应用程序会话状态持续性。如果将该值设置为 true,那么服务器将为每个连接创建 Session 对象,可访问会话状态,允许会话存储,出现 Session_OnStart Session_OnEnd 事件,并且发送 ASPSessionID Cookie 到客户端。如果将该值设置为 false,那么不允许状态访问和存储,事件将不进行处理,并且也不发送 Cookie
AspAppServiceFlags = 0
包含在 IIS 应用程序上启用 COM+ 服务所必须要设置的标志
AspBufferingLimit = 4194304
设置 ASP 缓冲区的最大大小。如果启动了响应缓冲,该属性将控制在进行刷新前 ASP 页面可以向响应缓冲区写入的最大字节数
AspBufferingOn = True
ASP
应用程序的输出是否需要缓冲
AspCalcLineNumber = True
ASP
是否计算和存储已执行代码的行号,以便在错误报告中提供
AspCodepage = 0
为应用程序指定默认的代码页
AspDiskTemplateCacheDirectory = %windir%/system32/inetsrv/ASP Comp
目录的名称,该目录是 ASP 在存储器内的缓存溢出后,用来将已编译的 ASP 模板存储到磁盘的目录
      
AspEnableApplicationRestart = True
确定 ASP 应用程序能否自动重新启动
AspEnableAspHtmlFallback = False
当由于请求队列已满而拒绝新的请求时,AspEnableAspHtmlFallback 属性控制 ASP 的行为。将该属性设置为 true,将导致发送与请求的 .asp 文件名称类似的 .htm 文件(如果存在),而不是发送 .asp 文件。.htm 文件的命名约定是 .asp 文件名之后附加一个 _asp。例如,.asp 文件是 hello.asp,那么 .htm 文件应该是 hello_asp.htm
AspEnableChunkedEncoding = True
指定是否为万维网发布服务(WWW 服务)启动 HTTP 1.1 chunked 传输编码
AspEnableParentPaths = False
页面是否允许当前目录的相对路径(使用 ../ 表示法)。
AspEnableSxs = False
true 将启动 COM+ 并排集合,该程序集允许 ASP 应用程序指定要使用哪个版本的系统 DLL 或传统 COM 组件,例如 MDACMFSMSVCRTMSXML 等等。
AspEnableTracker = False
true 将启动 COM+ 跟踪器,管理员或开发人员可用其来调试 ASP 应用程序。
AspEnableTypelibCache = True
是否在服务器上缓存类型库
AspErrorsToNTLog = False
是否将 IIS 脚本错误写入到 Windows 事件日志中
AspExceptionCatchEnable = True
页面是否捕获组件产生的异常。如果设置为 false (或者禁用),那么 Microsoft 脚本调试程序工具将不捕捉所调试的组件发生的异常。
AspExecuteInMTA = 0
ASP
能够在一个多线程单元 (MTA) 中运行其全部线程。如果 COM 组件主要是自由线程或双线程组件,则将 ASP 线程作为 MTA 运行可显著改善性能。默认情况下,AspExecuteInMTA 属性设置为 0,这意味着 ASP 不在 MTA 中执行。在应用程序级别上将该属性设置为 1 可以使 ASP MTA 中运行。
AspKeepSessionIDSecure = 0
启用 AspKeepSessionIDSecure 属性后,它可以确保将 SessionID 作为安全 Cookie 发送(如果已在安全通道上分配的话)。
AspLCID = 2048
用程序指定默认的区域设置标识符 (LCID)
AspLogErrorRequests = True
控制 Web 服务器是否将失败的客户请求写入到 Windows 事件日志文件中
AspMaxDiskTemplateCacheFiles = 2000
指定存储已编译 ASP 模板的最大数量。存储已编译模板的目录由 AspDiskTemplateCacheDirectory 属性配置。
AspMaxRequestEntityAllowed = 204800
指定一个 ASP 请求的实体正文中允许的最多字节数。
AspPartitionID =
COM+
分区用于将 Web 应用程序隔离到其各自的 COM+ 分区。COM+ 分区保存不同的自定义 COM 组件的版本。将 AspPartitionID 属性设置为 COM+ 分区的全局唯一标识符 (GUID)。同时,设置 AspAppServiceFlags 配置数据库属性的 AspUsePartition 标志。在应用程序级别设置这两个属性
AspProcessorThreadMax = 25
指定 IIS 可创建的每个处理器的最大工作线程数
AspQueueConnectionTestTime = 3
IIS
将所有的 ASP 请求放置到队列中。如果请求在队列中等待的时间比 AspQueueConnectionTestTime 属性指定的时间(以秒为单位)长,则 ASP 将在执行请求前检查确定客户端是否仍是连接的。如果客户端已断开连接,则不处理该请求并且从队列中删除该请求。
AspQueueTimeout = -1
允许 ASP 脚本请求在队列中等待的时间(以秒为单位)。无穷大表示为 -1
AspRequestQueueMax = 3000
允许进入队列的并发 ASP 请求的最大数目。在队列占满时,任何试图请求 ASP 文件的客户端浏览器都将收到 HTTP 500“服务器太忙”的错误。
AspRunOnEndAnonymously = True
指定了 SessionOnEnd ApplicationOnEnd 全局 ASP 函数是否应该作为匿名用户运行
AspScriptEngineCacheMax = 250
页面将在内存中保持缓存的脚本引擎的最大数目
AspScriptErrorMessage = 处理 URL 时服务器出错。请与系统管理员联系。    特殊调试错误没有被发送到客户端时(如果将 AspScriptErrorSentToBrowser 设置成 false)将发送给浏览器的错误消息
AspScriptErrorSentToBrowser = True
Web
服务器是否将调试细节(文件名、错误、行号、描述)写到客户端浏览器,并且记录到 Windows 事件日志中
AspScriptFileCacheSize = 500
要缓存的预编译脚本文件数。如果设置为 0,则不缓存任何脚本文件
AspScriptLanguage = VBScript
运行在 Web 服务器上的所有 ASP 应用程序的默认脚本语言
AspScriptTimeout = 90
AspScriptTimeout
属性指定了在终止脚本和将事件写入 Windows 事件日志之前,ASP 页面允许的脚本运行时间的默认值(以秒为单位)。
AspSessionMax = -1
IIS
允许的最大并发会话数。当达到该限制时,如果客户端试图与 IIS 建立新连接,则客户端将接收到错误信息(HTTP 500“服务器太忙”)。无穷大表示为 -1
AspSessionTimeout = 20
完成最后的与 Session 对象相关的请求后,保留该对象的时间(以分钟为单位)。
AspSxsName =
启动并行 (SxS) 程序集。并行 (SxS) 程序集允许 ASP 应用程序指定要使用哪个版本的系统 DLL 或传统 COM 组件,例如 MDACMFSMSVCRTMSXML 等。
AspTrackThreadingModel = False
IIS
是否检查应用程序创建的任意组件的线程模块。
AspUsePartition = False
true 将启动 COM+ 分区,可用其将 Web 应用程序隔离到各自的 COM+ 分区。COM+ 分区可拥有不同的自定义 COM 组件的版本。如果设置该标志,请同时设置 AspPartitionID 配置数据库属性。
AuthAdvNotifyDisable = True
禁用密码到期预先通知
AuthAnonymous = True
指定匿名身份验证作为可能的 Windows 验证方案之一,返回给客户端作为有效验证方案。
AuthBasic = False
指定基本身份验证作为可能的 Windows 验证方案之一,返回给客户端作为有效验证方案。
AuthChangeDisable = True
禁止更改密码
AuthChangeUnsecure = False
允许在不安全端口更改密码
AuthChangeURL = /iisadmpwd/achg.asp
用户输入新密码时被调用的 URL
AuthExpiredUnsecureURL = /iisadmpwd/aexp3.asp
用户密码到期时调用的 URL
AuthExpiredURL = /iisadmpwd/aexp.asp
用户密码到期时调用的 URL。将以安全的 (HTTPS) 方式调用它。
AuthFlags = 5
作为有效方案返回给客户端的 Windows 验证方案的设置
AuthMD5 = False
指定摘要式身份验证和高级摘要式身份验证作为可能的 Windows 验证方案之一,返回给客户端作为有效验证方案。
AuthNotifyPwdExpUnsecureURL = /iisadmpwd/anot3.asp
包含一个特定的 URL:如果用户的密码在 PasswordExpirePreNotifyDays 中指定的天数前到期,则调用该 URL
AuthNotifyPwdExpURL = /iisadmpwd/anot.asp
包含一个特定的 URL:如果用户的密码在 PasswordExpirePreNotifyDays 中指定的天数前到期,则调用该 URL。将以安全的 (HTTPS) 方式调用它。
AuthNTLM = True
指定集成 Windows 身份验证(也称作质询/响应或 NTLM 验证)作为可能的 Windows 验证方案之一,返回给客户端作为有效验证方案。
AuthPassport = False
true
的值表示启用了 Microsoft® .NET Passport 身份验证
AuthPersistence = 64
指定了使用 NTLM 验证跨越连接上的请求时的验证持久性
AuthPersistSingleRequest = True
将该标志设置成 true 指定验证仅对一个连接上的单个请求持久。IIS 在每个请求的末尾重设验证,并且在会话的下一个请求上强制执行重验证。
AzEnable = False
用于虚拟目录、应用程序,或配置数据库中项相应的 URL URL 授权。
AzImpersonationLevel = 0
用于应用程序的模拟行为,该模拟行为允许配置 Web 应用程序模拟客户端用户、IIS 工作进程,或工作进程的 IUSER_* 帐户。
AzScopeName =
将虚拟目录、应用程序或 URL 与作用域相关联。如果没有指定作用域或指定了空子符串,则使用 IIS 6.0 URL 授权的默认作用域。
AzStoreName =
授权管理器策略存储与虚拟目录、应用程序或 URL 相关联。
CacheControlCustom =
指定了自定义 HTTP 1.1 缓存控制指令。
CacheControlMaxAge = 0
指定了 HTTP 1.1 缓存控制最大时间值。
CacheControlNoCache = False
保护缓存内容的 HTTP 1.1 指令
CacheISAPI = True
在第一次使用 ISAPI 扩展后是否在内存中进行缓存。
Caption =
提供对象的一段简短文本描述(一行字符串)。
CGITimeout = 300
指定 CGI 应用程序超时(以秒为单位)。
ContentIndexed = True
指定安装的目录索引程序是否应该检索该目录树下的内容。
CreateCGIWithNewConsole = False
指示 CGI 应用程序是否在自己的控制台上运行。
CreateProcessAsUser = True
是在系统环境中创建 CGI 进程还是在请求用户环境中创建 CGI 进程。
DefaultDoc = index.aspx,default.aspx
包含一个或多个默认文档的文件名,如果在客户端的请求中不包含文件名,将把默认文档的文件名返回给客户端。
DefaultDocFooter =
附加到返回到客户端的 HTML 文件的自定义页脚(页脚并不附加到 ASP 文件)。
DefaultLogonDomain =
服务器用来对用户进行身份验证的默认域(在 UserIsolationMode = 2 Web 宿主方案中)。
Description =
提供对象的一段较长文本描述。
DirBrowseFlags = 1073741886

可以提供多少目录和文件信息(如果启用浏览)以及目录中是否包含默认页的标记。
DirBrowseShowDate = True
设置为 true 时,浏览目录时将显示日期信息。
DirBrowseShowExtension = True
设置为 true 时,浏览目录时将显示文件扩展名。
DirBrowseShowLongDate = True
设置为 true 时,显示目录时将在扩展格式中显示日期信息。
DirBrowseShowSize = True
设置为 true 时,浏览目录时将显示文件大小信息。
DirBrowseShowTime = True
设置为 true 时,显示目录时将显示文件时间信息。
DisableStaticFileCache = False
目录的静态文件缓存
DoDynamicCompression = False
HcDoDynamicCompression 属性相同。
DontLog = False
是否将客户端的请求写入日志文件。
DoStaticCompression = False
HcDoStaticCompression 属性相同。
EnableDefaultDoc = True
设置为 true 时,浏览目录时系统会加载该目录的默认文档(由 DefaultDoc 属性指定)。
EnableDirBrowsing = False
设置为 true 时,将启用目录浏览。
EnableDocFooter = False
启用或禁用由 DefaultDocFooter 属性指定的自定义页脚。
EnableReverseDns = False
启用或禁用万维网发布服务(WWW 服务)的反向域名服务器 (DNS) 查找。
FrontPageWeb = True
服务器实例是否由 Microsoft® FrontPage® 处理。
HttpExpires = D, 0x15180
在返回给浏览器的 HTML 文件标头中指定数值,来指定 HTML 文档的过期时间。
HttpRedirect =
当客户端试图访问特定资源时,重定向到的目录或 URL
LogonMethod = 3
指定明文登录的登录方法的整数。
MaxRequestEntityAllowed = -1
请求实体正文中允许的最大字节数。无穷大表示为 -1
Name = W3SVC/1/ROOT
定义了用来识别对象的标签。创建子类时,可以将 Name 属性改写为 Key 属性。
NTAuthenticationProviders =
以逗号分隔的 Windows 身份验证提供程序列表,例如集成 Windows 身份验证(也称为 NTLM)。
PassportRequireADMapping = 1
IIS
如何处理 Microsoft .NET Passport 验证和 Active Directory 映射。
PasswordChangeFlags = 6
控制服务器和客户端之间密码到期及密码更改处理的标志。默认值 0 表示需要 SSL 连接;1 表示允许在非安全端口进行更改;2 表示禁止更改;4 表示禁用密码到期通知。
PasswordExpirePrenotifyDays = 0
距离客户端密码到期时间的天数,还显示发送密码预先通知消息的时间。
Path = D:/XXXX/XXXXX/XXXXX
与虚拟目录关联的物理路径。
PoolIdcTimeout = 0
Internet
数据库连接池的超时值(秒)。值 0 表示未执行任何池。
Realm =
IIS
用来验证客户端的领域,该客户端试图访问由摘要式身份验证或高级摘要式身份验证保护的资源。
SettingID =
由已知 CIM_Setting 对象指定了标识。
ShutdownTimeLimit = 90
在达到回收阈值后,IIS 应等待多长时间(以秒为单位)以便所有旧请求在工作进程结束之前完成运行。
SSIExecDisable = False
是否禁用此路径下的在服务器端的包含文件 (SSI) #exec 指令。
UNCPassword =
在获取 UNC(通用命名约定)虚拟根访问权限时使用的加密密码
UNCUserName =
为通用命名约定 (UNC) 虚拟根指定用户名
UploadReadAheadSize = 49152
确定 Web 服务器读入缓冲区并传递到 ISAPI 扩展的字节数。
UseDigestSSP = False
由高级摘要式身份验证用来在摘要式或高级摘要式安全支持提供程序接口 (SSPI) 代码之间切换。
WebDAVMaxAttributesPerElement = 32
??

Win32Error = 0

Microsoft Win32
错误状态代码

http://blog.csdn.net/cqfeng/archive/2006/02/14/598943.aspx

ServerBindings - IP:端口号:主机头
ServerComment - 描述
AppFriendlyName - 应用程序名
AppIsolated - 值 0 表示应用程序在进程内运行,值 1 表示进程外,值 2 表示进程池
AccessFlags - 简单点说,AccessFlags属性值就是由AccessRead(1),AccessScript(512),AccessExecute(4;等等的值相加而得来的,如:需要配置站点的执行权限为纯脚本,使用AccessRead(1)+AccessScript(512),得出的值是513,在设置IIS站点时,直接赋予AccessFlags属性值为513就可以了
AppRoot = /LM/W3SVC/1(siteID)/ROOT
包含到应用程序根目录的配置数据库路径。
Path路径

http://west-wind.com/weblog/posts/399.aspx


I was futzing around today with installation of one of my Web applications. Automatic installation of apps as to where they can be fully self-installed has always been a thing that I like to do, but it’s difficult to get this right with the ‘lower end’ installer tools and it’s a major PITA (not to mention an expensive undertaking) when dealing with the high end installer tools that do support that sort of thing well.

My typical install scenarios are these:

  • Allow selection of a Web Site to install to Create a Virtual Directory Possibly set up alternate script maps
  • If running IIS set up an Application Pool

I haven’t gotten around to the latter two items, but I did start building a small wrapper class that retrieves a list of Web Sites installed locally (or on a remote machine) and allows creation of a virtual directory with the most common settings.

The following VirtualDirectory class is a pretty basic implementation that does the core functions that I typically need when creating a virtual directory. If you look at the public field list you can get a pretty good idea what options I implemented. Obviously not everything is covered here, but it sure is nicer to call the CreateVirtual() method than jerking around with the DirectoryEntry class. The following C# class handles these base tasks for me:

public class VirtualDirectory
{

public WebServerType ServerType = WebServerType.IIS6;

public string Virtual = "";
public string FriendlyName = "";
public string Path = "";
public string IISPath = "IIS://LOCALHOST/W3SVC/1/ROOT";
public string ApplicationPool = "";
// n/a

public bool AuthNTLM = true;
public bool AuthAnonymous = true;
public bool AuthBasic = true;
public string DefaultDocuments = "default.htm,default.aspx,default.asp";


///

/// Used for GetWebSites to retrieve sites for a given domain or IP
///

public string DomainName = "localhost";

///

/// Contains Virtual directory entry (as a DirectoryEntry object) after
/// the virtual was created.
///

public DirectoryEntry VDir = null;

///

/// Contains error message on a failure result.
///

public string ErrorMessage = "";


///

/// Returns a list of Web Sites on the local machine
///

///

public WebSiteEntry[] GetWebSites()
{

string Path = "IIS://" + this.DomainName + "/W3SVC";



DirectoryEntry root = null;


try


{


root = new DirectoryEntry(Path);


}


catch


{


this.SetError("Couldn't access root node");


return null;


}


if (root == null)


{


this.SetError("Couldn't access root node");


return null;


}



ArrayList al = new ArrayList(20);




foreach (DirectoryEntry Entry in root.Children)


{


PropertyCollection Properties = Entry.Properties;




try


{


WebSiteEntry Site = new WebSiteEntry();


Site.SiteName = (string) Properties["ServerComment"].Value;


Site.IISPath = Entry.Path;


al.Add(Site);


}


catch { ; }


}




root.Close();



return (WebSiteEntry[]) al.ToArray(typeof(WebSiteEntry));

}

///

/// Creates a Virtual Directory on the Web Server and sets a few
/// common properties based on teh property settings of this object.
///

///

public bool CreateVirtual()
{

this.SetError(null);



DirectoryEntry root= new DirectoryEntry(this.IISPath);


if (root == null)


{


this.SetError("Couldn't access root node");


return false;


}



try


{


this.VDir = root.Children.Add(Virtual,"IISWebVirtualDir");


}


catch


{


try { this.VDir= new DirectoryEntry(this.IISPath + "/" + Virtual); }


catch {;}


}



if (this.VDir == null)


{


this.SetError("Couldn't create virtual.");


return false;


}




root.CommitChanges();


VDir.CommitChanges();



return this.SaveVirtualDirectory();

}

public bool SaveVirtualDirectory()
{

PropertyCollection Properties = VDir.Properties;



try


{


Properties["Path"].Value = Path;


}


catch (Exception ex)


{


this.SetError("Invalid Path provided " + ex.Message);


return false;


}



this.VDir.Invoke("AppCreate",true);


if (this.FriendlyName == "")


VDir.Properties["AppFriendlyName"].Value = Virtual;


else


VDir.Properties["AppFriendlyName"].Value = this.FriendlyName;



if (this.DefaultDocuments != "")


VDir.Properties["DefaultDoc"].Value = this.DefaultDocuments;



int Flags = 0;


if (this.AuthAnonymous)


Flags = 1;


if (this.AuthBasic)


Flags = Flags + 2;


if (this.AuthNTLM)


Flags = Flags + 4;


Properties["AuthFlags"].Value = Flags;
// NTLM AuthBasic Anonymous



VDir.CommitChanges();



return true;

}
protected void SetError(string ErrorMessage)
{

if (ErrorMessage == null)


this.ErrorMessage = "";



this.ErrorMessage = ErrorMessage;

}

}
public enum WebServerType
{

IIS4, IIS5, IIS6

}

There is also a WebSiteEntry class that’s used to capture the list of Web Sites when calling the GetWebSites() method which returns an array of these objects.

public class WebSiteEntry
{

public string SiteName = "";


public string Comment = "";


public string IISPath = "";

}

Working with DirectoryEntry and especially VDir.Properties collection is not a lot of fun. I had a hell of a time trying to get this collection to work correctly. Originally I was referencing the collection directly off the VDir class. For some unknown reason this did not work until I moved the collection off onto a separate variable. This did not work:

string Path = (string) VDir.Properties["Path"];

But this did:

PropertyCollection Properties = VDir.Properties;
string Path = (string) Properties["Path"];
                  
Go figure. By the way, if you need to find documentation in MSDN on what properties are available do a search on IIsWebVirtualDir, which will give you a list of all the settings available. I’m glad to see Microsoft moved the ADSI settings back into MSDN more visibly in recent versions of MSDN – about a year ago, the new WMI settings were the only ones that I could find.

To utilize the class, here is an example of how I use it in my West Wind Web Store configuration application. This app runs as desktop app as a Post install executable and handles a bunch of configuration tasks for the application, such as creating the SQL database, configuring the Web Site. This is then followed by further configuration once the Web Site is configured via a ASP. Net based application configuration.

The following two snippets deal with displaying a list of Web Sites to the user and then allowing the user to select a Web Site, virtual path name with a physical path pointing at the current installation directory.

The following loads a list of sites into a dropdown box:

private void LoadSites()
{

VirtualDirectory vd = new VirtualDirectory();


Sites = vd.GetWebSites();


if (Sites == null)


{


MessageBox.Show("Couldn't read IIS Configuration/r/n" +



"Make sure IIS is installed on this machine.",


"Web Monitor",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);


}



for (int x=0; x < Sites.Length; x++)


{


this.lstSites.Items.Add(Sites[x].SiteName);


}


if (Sites.Length > 0)


this.lstSites.SelectedIndex = 0;


}

To actually create a virtual directory I then pick the user’s selection and go with their choice:

private void btnCreateVDir_Click(object sender, System.EventArgs e)
{

int lnIndex = this.lstSites.SelectedIndex;


if (lnIndex < 0)


return;



VirtualDirectory Virtual = new VirtualDirectory();


Virtual.Virtual = this.txtVirtual.Text;


Virtual.Path = this.txtPath.Text;


Virtual.IISPath = this.Sites[lnIndex].IISPath + "/ROOT";



if ( Virtual.CreateVirtual() )


{


MessageBox.Show("Virtual Directory " + Virtual.Virtual + " created.")


this.VirtualCreated = true;


}


else


MessageBox.Show("Virtual Directory " + Virtual.Virtual +


" failed to create./r/n/r/n" +


Virtual.ErrorMessage + "/r/n/r/n")

}

I’ve used this sort of thing in several of my Web apps thus far and it’s worked out great – I have had no support calls on this stuff where with default installs going to the default Web Site I’ve often had major issues either because the server wasn’t properly dealing with localhost (especially in multi-homed servers).

I hope somebody finds the above useful, because it sure saves me a lot of time now when building new Web installations.

 

 

 

 

 

 

 

 

 

 

 

Set   DirObj   =   ServerObj.Create("IIsWebVirtualDir",   VirtualDir)   
            
          DirObj.Path   =   SourceDir   
          DirObj.AccessRead   =   True   
          DirObj.AccessWrite   =   False   
          DirObj.EnableDirBrowsing   =   False     
          DirObj.AccessScript=True   
          DirObj.EnableDefaultDoc   =   True   
          DirObj.AuthAnonymous   =   False   
          DirObj.AuthBasic   =   False   
          DirObj.AuthNTLM   =   True   
          DirObj.AppCreate   INPROC

 

 

C# 通过ADSI在Active Directory中新建帐号,以及开通Exchange中的邮箱

///   <summary>   
  ///   添加AD用户   
  ///   </summary>   
  ///   <returns>是(true)否(false)成功</returns>   
  public   bool   AddUser()   
  {   
  bool   fblnResult=false;   
  try   
  {   
  RootDSE=RootDSE.Insert(7,GetOU(sUnitCode.Trim()));//添加OU   
  //RootDSE=sRootDSE.Insert(7,"CN=Users,");   
  DirectoryEntry   myDE   =   new   DirectoryEntry(RootDSE);   
  DirectoryEntries   myEntries   =   myDE.Children;   
   
  DirectoryEntry   myDirectoryEntry   =     
  myEntries.Add("CN="+sName.Trim(),   "user");//_oRequest.sUserName.Trim()   
  //MessageBox.Show(myDirectoryEntry.SchemaClassName.ToString());   
   
  myDirectoryEntry.Properties["userPrincipalName"].Value="";   
  myDirectoryEntry.Properties["samAccountName"].Value="";   
  myDirectoryEntry.Properties["userAccountControl"].Value   =66048;//启用账号,546为禁用   
  myDirectoryEntry.Properties["postalCode"].Value   =   "";   
   
   
  //*****************************************************Exchange信箱*********************   
  // myDirectoryEntry.Properties["homeMTA"].Value="CN=Microsoft   MTA,CN=这里是服务器名,CN=Servers,CN=First   Administrative   Group,CN=Administrative   Groups,CN=域名   Organization,CN=Microsoft   Exchange,CN=Services,CN=Configuration,这里是你的DC字符串(如dc=,dc=)";   
  // myDirectoryEntry.Properties["msExchHomeServerName"].Value="/o=域名   Organization/ou=First   Administrative   Group/cn=Configuration/cn=Servers/cn=这里是服务器名";   
  // myDirectoryEntry.Properties["homeMDB"].Value="CN=Mailbox   Store   (这里是服务器名),CN=First   Storage   Group,CN=InformationStore,CN=这里是服务器名,CN=Servers,CN=First   Administrative   Group,CN=Administrative   Groups,CN=域名   Organization,CN=Microsoft   Exchange,CN=Services,CN=Configuration,这里是你的DC字符串(如dc=,dc=)";   
  // myDirectoryEntry.Properties["mailNickname"].Value="";   
  // myDirectoryEntry.Properties["mDBUseDefaults"].Value=true;   
  // myDirectoryEntry.Properties["msExchALObjectVersion"].Value=53;//需要根据情况设置   
  // myDirectoryEntry.Properties["msExchUserAccountControl"].Value=0;   
  // myDirectoryEntry.Properties["textEncodedORAddress"].Value="c=us;a=   ;p=域名   Organizati;o=Exchange;s=用户的账号;";   
  // myDirectoryEntry.Properties["mail"].Value="电子邮件地址";   
   
   
  myDirectoryEntry.CommitChanges();   
   
  fblnResult=true;   
  }   
  catch(Exception   e)   
  {   
  //弹出错误   
  MessageBox.Show(e.Message.Trim(),"提示:",MessageBoxButtons.OK,MessageBoxIcon.Error,   
  MessageBoxDefaultButton.Button1,MessageBoxOptions.DefaultDesktopOnly);   
  }   
  return   fblnResult;   
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值