//-----------------------------------------------------------------------//// Copyright (c) 2016 , All rights reserved.// //-----------------------------------------------------------------------using System;using Microsoft.Web.Administration;namespace DotNet.MVCInfrastructure.Helpers{ using DotNet.Utilities; ////// IIS应用 /// Microsoft中提供了管理IIS7的一些非常强大的API——Microsoft.Web.Administration, /// 可以很方便的让我们以编程的方式管理,设定IIS 7的各项配置。 /// Microsoft.Web.Administration.dll位于IIS的目录(%WinDir%\System32\InetSrv)下, /// 在项目中添加对其的引用后您就可以使用这些API了 /// /// /// 错误: 由于权限不足而无法读取配置文件 文件名: redirection.config /// 解决办法 选择该网站的应用程序池的高级设置里进程模型下的标识选择为LocalSystem /// /// 修改纪录 /// /// 2018-09-10版本:1.0 SongBiao 创建文件。 /// /// public partial class IISHelper { ////// ///SongBiao ///2018-09-10 ////// 停止一个站点 /// public static BaseResult StopSite(string site) { BaseResult result = BaseResult.Fail("未知错误"); try { ServerManager iisManager = new ServerManager(); if (iisManager.Sites[site].State == ObjectState.Stopped || iisManager.Sites[site].State == ObjectState.Stopping) { result.Status = true; result.StatusMessage = site + ":站点已停止"; } else { ObjectState state = iisManager.Sites[site].Stop(); if (state == ObjectState.Stopping || state == ObjectState.Stopped) { result.Status = true; result.StatusMessage = site + ":站点已停止"; } else { result.Status = false; result.StatusMessage = site + ":站点停止失败"; } } } catch (Exception ex) { NLogHelper.Warn(ex, " public static BaseResult StopSite(string site)"); result.Status = false; result.StatusMessage = site + ":站点停止出现异常:" + ex.Message; } return result; } ////// 启动一个站点 /// public static BaseResult StartSite(string site) { BaseResult result = BaseResult.Fail("未知错误"); try { ServerManager iisManager = new ServerManager(); if (iisManager.Sites[site].State != ObjectState.Started || iisManager.Sites[site].State != ObjectState.Starting) { ObjectState state = iisManager.Sites[site].Start(); if (state == ObjectState.Starting || state == ObjectState.Started) { result.Status = true; result.StatusMessage = site + ":站点已启动"; } else { result.Status = false; result.StatusMessage = site + ":站点停止失败"; } } else { result.Status = true; result.StatusMessage = site + ":站点已是启动状态"; } } catch (Exception ex) { NLogHelper.Warn(ex, " public static BaseResult StartSite(string site)"); result.Status = false; result.StatusMessage = site + ":站点停止出现异常:" + ex.Message; } return result; } ////// 停止应用程序池 /// /// public static BaseResult StopApplicationPool(string appPool = null) { BaseResult result = BaseResult.Fail("未知错误"); try { if (string.IsNullOrWhiteSpace(appPool)) { appPool = Environment.GetEnvironmentVariable("APP_POOL_ID", EnvironmentVariableTarget.Process); } ServerManager iisManager = new ServerManager(); if (iisManager.ApplicationPools[appPool].State == ObjectState.Stopped || iisManager.ApplicationPools[appPool].State == ObjectState.Stopping) { result.Status = true; result.StatusMessage = appPool + ":应用程序池已停止"; } else { ObjectState state = iisManager.ApplicationPools[appPool].Stop(); if (state == ObjectState.Stopping || state == ObjectState.Stopped) { result.Status = true; result.StatusMessage = appPool + ":应用程序池已停止"; } else { result.Status = false; result.StatusMessage = appPool + ":应用程序池停止失败,请重试"; } } } catch (Exception ex) { NLogHelper.Warn(ex, " public static BaseResult StopApplicationPool(string appPool = null)"); result.Status = false; result.StatusMessage = appPool + ":应用程序池失败出现异常:" + ex.Message; } return result; } ////// 启动应用程序池 /// /// public static BaseResult StartApplicationPool(string appPool = null) { BaseResult result = BaseResult.Fail("未知错误"); try { if (string.IsNullOrWhiteSpace(appPool)) { appPool = Environment.GetEnvironmentVariable("APP_POOL_ID", EnvironmentVariableTarget.Process); } ServerManager iisManager = new ServerManager(); if (iisManager.ApplicationPools[appPool].State != ObjectState.Started || iisManager.ApplicationPools[appPool].State != ObjectState.Starting) { ObjectState state = iisManager.ApplicationPools[appPool].Start(); if (state == ObjectState.Starting || state == ObjectState.Started) { result.Status = true; result.StatusMessage = appPool + ":应用程序池已启动"; } else { result.Status = false; result.StatusMessage = appPool + ":应用程序池启动失败,请重试"; } } else { result.Status = true; result.StatusMessage = appPool + ":应用程序池已是启动状态"; } } catch (Exception ex) { NLogHelper.Warn(ex, " public static BaseResult StartApplicationPool(string appPool = null)"); result.Status = false; result.StatusMessage = appPool + ":应用程序池启动出现异常:" + ex.Message; } return result; } ////// 回收应用程序池 /// /// public static BaseResult RecycleApplicationPool(string appPool = null) { BaseResult result = BaseResult.Fail("未知错误"); try { if (string.IsNullOrWhiteSpace(appPool)) { appPool = Environment.GetEnvironmentVariable("APP_POOL_ID", EnvironmentVariableTarget.Process); } ServerManager iisManager = new ServerManager(); ObjectState state = iisManager.ApplicationPools[appPool].Recycle(); result.Status = true; result.StatusMessage = appPool + ":应用程序池回收成功:"+ state; } catch (Exception ex) { NLogHelper.Warn(ex, " public static BaseResult StartApplicationPool(string appPool = null)"); result.Status = false; result.StatusMessage = appPool + ":应用程序池回收出现异常:" + ex.Message; } return result; } ////// 运行时控制:得到当前正在处理的请求 /// /// public static void GetWorking(string appPool) { ServerManager iisManager = new ServerManager(); foreach (WorkerProcess w3wp in iisManager.WorkerProcesses) { Console.WriteLine("W3WP ({0})", w3wp.ProcessId); foreach (Request request in w3wp.GetRequests(0)) { Console.WriteLine("{0} - {1},{2},{3}", request.Url, request.ClientIPAddr, request.TimeElapsed, request.TimeInState); } } } ////// 获取IIS日志文件路径 /// ///public static string GetIISLogPath() { ServerManager manager = new ServerManager(); // 获取IIS配置文件:applicationHost.config var config = manager.GetApplicationHostConfiguration(); var log = config.GetSection("system.applicationHost/log"); var logFile = log.GetChildElement("centralW3CLogFile"); //获取网站日志文件保存路径 var logPath = logFile.GetAttributeValue("directory").ToString(); return logPath; } /// ///创建新站点 /// /// /// "*:<port>:<hostname>""*:80:myhost.com" /// public static void CreateSite(string siteName, string bindingInfo, string physicalPath) { createSite(siteName, "http", bindingInfo, physicalPath, true, siteName + "Pool", ProcessModelIdentityType.NetworkService, null, null, ManagedPipelineMode.Integrated, null); } ////// 创建新站点 /// /// /// /// /// /// /// /// /// /// /// /// private static void createSite(string siteName, string protocol, string bindingInformation, string physicalPath, bool createAppPool, string appPoolName, ProcessModelIdentityType identityType, string appPoolUserName, string appPoolPassword, ManagedPipelineMode appPoolPipelineMode, string managedRuntimeVersion) { using (ServerManager mgr = new ServerManager()) { Site site = mgr.Sites.Add(siteName, protocol, bindingInformation, physicalPath); // PROVISION APPPOOL IF NEEDED if (createAppPool) { ApplicationPool pool = mgr.ApplicationPools.Add(appPoolName); if (pool.ProcessModel.IdentityType != identityType) { pool.ProcessModel.IdentityType = identityType; } if (!String.IsNullOrEmpty(appPoolUserName)) { pool.ProcessModel.UserName = appPoolUserName; pool.ProcessModel.Password = appPoolPassword; } if (appPoolPipelineMode != pool.ManagedPipelineMode) { pool.ManagedPipelineMode = appPoolPipelineMode; } site.Applications["/"].ApplicationPoolName = pool.Name; } mgr.CommitChanges(); } } ////// Delete an existent web site. /// /// Site name. public static void DeleteSite(string siteName) { using (ServerManager mgr = new ServerManager()) { Site site = mgr.Sites[siteName]; if (site != null) { mgr.Sites.Remove(site); mgr.CommitChanges(); } } } ////// 创建虚拟目录 /// /// /// /// public static void CreateVDir(string siteName, string vDirName, string physicalPath) { using (ServerManager mgr = new ServerManager()) { Site site = mgr.Sites[siteName]; if (site == null) { throw new ApplicationException(String.Format("Web site {0} does not exist", siteName)); } site.Applications.Add("/" + vDirName, physicalPath); mgr.CommitChanges(); } } ////// 删除虚拟目录 /// /// /// public static void DeleteVDir(string siteName, string vDirName) { using (ServerManager mgr = new ServerManager()) { Site site = mgr.Sites[siteName]; if (site != null) { Microsoft.Web.Administration.Application app = site.Applications["/" + vDirName]; if (app != null) { site.Applications.Remove(app); mgr.CommitChanges(); } } } } ////// Delete an existent web site app pool. /// /// App pool name for deletion. public static void DeletePool(string appPoolName) { using (ServerManager mgr = new ServerManager()) { ApplicationPool pool = mgr.ApplicationPools[appPoolName]; if (pool != null) { mgr.ApplicationPools.Remove(pool); mgr.CommitChanges(); } } } ////// 在站点上添加默认文档。 /// /// /// public static void AddDefaultDocument(string siteName, string defaultDocName) { using (ServerManager mgr = new ServerManager()) { Configuration cfg = mgr.GetWebConfiguration(siteName); ConfigurationSection defaultDocumentSection = cfg.GetSection("system.webServer/defaultDocument"); ConfigurationElement filesElement = defaultDocumentSection.GetChildElement("files"); ConfigurationElementCollection filesCollection = filesElement.GetCollection(); foreach (ConfigurationElement elt in filesCollection) { if (elt.Attributes["value"].Value.ToString() == defaultDocName) { return; } } try { ConfigurationElement docElement = filesCollection.CreateElement(); docElement.SetAttributeValue("value", defaultDocName); filesCollection.Add(docElement); } catch (Exception) { } //this will fail if existing mgr.CommitChanges(); } } ////// 检查虚拟目录是否存在。 /// /// /// ///public static bool VerifyVirtualPathIsExist(string siteName, string path) { using (ServerManager mgr = new ServerManager()) { Site site = mgr.Sites[siteName]; if (site != null) { foreach (Microsoft.Web.Administration.Application app in site.Applications) { if (app.Path.ToUpper().Equals(path.ToUpper())) { return true; } } } } return false; } /// /// 检查站点是否存在。 /// /// ///public static bool VerifyWebSiteIsExist(string siteName) { using (ServerManager mgr = new ServerManager()) { for (int i = 0; i < mgr.Sites.Count; i++) { if (mgr.Sites[i].Name.ToUpper().Equals(siteName.ToUpper())) { return true; } } } return false; } /// /// 检查Bindings信息。 /// /// ///public static bool VerifyWebSiteBindingsIsExist(string bindingInfo) { string temp = string.Empty; using (ServerManager mgr = new ServerManager()) { for (int i = 0; i < mgr.Sites.Count; i++) { foreach (Microsoft.Web.Administration.Binding b in mgr.Sites[i].Bindings) { temp = b.BindingInformation; if (temp.IndexOf('*') < 0) { temp = "*" + temp; } if (temp.Equals(bindingInfo)) { return true; } } } } return false; } }}