利用IIS7自带类库管理IIS现在变的更强大更方便,而完全可以不需要用DirecotryEntry这个类了(网上很多.net管理iis6.0的文章都用到了DirecotryEntry这个类 ),Microsoft.Web.Administration.dll位于IIS的目录(%WinDir%\System32\InetSrv)下,使用时需要引用,它基本上可以管理IIS7的各项配置。
这个类库的主体结构如下:
前端代码
<%@ Page Title="IIS管理" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Manager.aspx.cs" Inherits="IISManager.Ide.Net.Cn.Manager" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%:Page.Title %></h2>
<asp:Panel CssClass="panel panel-default" runat="server">
<div class="panel-body">
<asp:Label runat="server" CssClass="control-label">网站IP</asp:Label><asp:TextBox CssClass="form-control" Width="100%" runat="server" ID="txtIP" ClientIDMode="Static" ToolTip="网站名称">localhost</asp:TextBox>
<br />
<asp:Label runat="server" CssClass="control-label">网站名称</asp:Label><asp:TextBox CssClass="form-control" Width="100%" runat="server" ID="txtSiteName" ClientIDMode="Static" ToolTip="网站名称">test</asp:TextBox>
<br />
<asp:Label runat="server" CssClass="control-label">物理路径</asp:Label><asp:TextBox CssClass="form-control" Width="100%" runat="server" ID="txtPath" ClientIDMode="Static" ToolTip="网站路径">c:\test</asp:TextBox>
<br />
<asp:Label runat="server" CssClass="control-label">端口</asp:Label><asp:TextBox CssClass="form-control" Width="100%" runat="server" ID="txtPort" ClientIDMode="Static" ToolTip="网站端口">1234</asp:TextBox>
<br />
<asp:Button ID="btnAdd" EnableViewState="false" UseSubmitBehavior="false" runat="server" Text="提交" CssClass="btn btn-default" OnClick="btnAdd_Click"></asp:Button>
</div>
</asp:Panel>
</asp:Content>
后台代码
using Microsoft.Web.Administration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace IISManager.Ide.Net.Cn
{
public partial class Manager : Page
{
string ip = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (!ConfigurationManager.AppSettings.AllKeys.Contains("IP"))
{
Response.Write("<script>alert('config文件配置不正确')</script>");
Response.Write(" <script> window.close(); </script> ");
return;
}
ip = ConfigurationManager.AppSettings["IP"];
if (string.IsNullOrEmpty(ip))
{
Response.Write("<script>alert('请配置IP地址')</script>");
Response.Write(" <script> window.close(); </script> ");
return;
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
try
{
string siteName = txtSiteName.Text.Trim();
int port = Convert.ToInt32(txtPort.Text.Trim());
string path = txtPath.Text.Trim();
FileInfo fi = new FileInfo(path);
if ((fi.Attributes & FileAttributes.Directory) != 0)
{
}
else
{
Response.Write("<script>alert('文件路径无效')</script>");
}
ServerManager sm = ServerManager.OpenRemote(this.txtIP.Text.Trim());
//创建应用程序池
//先检测是否存在,如果存在不进行操作
//如果创建的应用程序池已经存在,系统不会进行创建
ApplicationPool appPool = sm.ApplicationPools.FirstOrDefault(x => x.Name == siteName);
if (appPool != null)
{
sm.ApplicationPools.Remove(appPool);
}
appPool = sm.ApplicationPools.Add(siteName);
appPool.AutoStart = true;//是否自动启动,true代表创建完成后自动启动
appPool.Enable32BitAppOnWin64 = false;//启动32位支持
appPool.ManagedPipelineMode = ManagedPipelineMode.Integrated;//托管管道模式Integrated = 0, Classic = 1
appPool.ManagedRuntimeVersion = "v4.0";//版本
appPool.QueueLength = 10000;//队列长度,如果操作限制将显示503
appPool.Recycling.PeriodicRestart.Time = new TimeSpan(0, 5, 0);//固定回收时间
appPool.ProcessModel.IdleTimeout = new TimeSpan(0, 5, 0);//5分钟闲置超时
appPool.ProcessModel.MaxProcesses = 1;//最大进程数
appPool.ProcessModel.PingingEnabled = true;//是否允许ping
appPool.ProcessModel.PingInterval = new TimeSpan(0, 0, 40);//ping间隔
appPool.ProcessModel.PingResponseTime = new TimeSpan(0, 0, 10);//ping最大相应时间 10秒
appPool.ProcessModel.ShutdownTimeLimit = new TimeSpan(0, 0, 50);//关闭时间限制
appPool.ProcessModel.StartupTimeLimit = new TimeSpan(0, 0, 50);//启动时间限制
//创建站点
Site site = sm.Sites.FirstOrDefault(x => x.Name == siteName);
if (site != null)
{
sm.Sites.Remove(site);
}
site = sm.Sites.Add(siteName, path, port);
site.ServerAutoStart = true;//自动启动
Application root = site.Applications["/"];
root.ApplicationPoolName = appPool.Name;//设置应用程序池
site.Bindings[0].EndPoint.Port = port;//终点端口号
site.Limits.MaxBandwidth = 2000000;//最大带宽
site.Limits.MaxConnections = 1000;//最大连接数
site.LogFile.Directory = path + "\\log";//日志文件路径
site.LogFile.Enabled = true;//开启日志
site.LogFile.LogExtFileFlags = LogExtFileFlags.Date;//日志文件形式
site.LogFile.LogFormat = LogFormat.Custom;//日志格式
site.LogFile.Period = LoggingRolloverPeriod.Hourly;//日志文件记录时间间隔
site.LogFile.TruncateSize = 1048577;//日志文件截取大小
site.TraceFailedRequestsLogging.MaxLogFiles = 100;//失败请求最大跟踪日志数量
site.TraceFailedRequestsLogging.Directory = path + "\\tracelog";//失败请求日志路径
site.TraceFailedRequestsLogging.Enabled = true;//启用失败请求跟踪
//site.SetAttributeValue("preloadEnabled", true);//启用预加载
sm.CommitChanges();
Response.Write("<script>alert('创建成功')</script>");
}
catch (Exception ex)
{
Response.Write("<script>alert('创建失败,请检查输入先是否正确')</script>");
}
}
}
}
配置文件
<?xml version="1.0"?>
<!--
有关如何配置 ASP.NET 应用程序的详细信息,请访问
https://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<!--
有关 web.config 更改的说明,请参见 http://go.microsoft.com/fwlink/?LinkId=235367。
可在 <httpRuntime> 标记上设置以下特性。
<system.Web>
<httpRuntime targetFramework="4.6.1" />
</system.Web>
-->
<appSettings>
<add key="SiteName" value="IIS管理系统"/>
<add key="IP" value="58.87.77.174"/>
</appSettings>
<system.web>
<identity impersonate="true" userName="administrator" password="123456"/>
<compilation debug="true" targetFramework="4.6.1"/>
<httpRuntime/>
<pages controlRenderingCompatibilityVersion="4.0">
<namespaces>
<add namespace="System.Web.Optimization"/>
</namespaces>
<controls>
<add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt"/>
</controls>
</pages>
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
</httpModules>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed"/>
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove name="ApplicationInsightsWebTracking"/>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler"/>
</modules>
</system.webServer>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
</compilers>
</system.codedom>
</configuration>
温馨提示
配置文件主要是identity
节点,配置登陆用户
谢谢
能用吗?谢谢分享