1,在Web上修改指定文件位置的Web.config

这里需要使用 WebConfigurationManager 类,但必须使用WebConfigurationFileMap类来指定文件位置,看代码:

long appId = 123;

 //修改网站的配置文件
 var configFile = new FileInfo(configFilePath);
 var vdm = new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);
 var wcfm = new WebConfigurationFileMap();
 wcfm.VirtualDirectories.Add("/", vdm);
 var config = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/", siteName);
 AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
 appSection.Settings["abc"].Value = "system tag";
 appSection.Settings["appId"].Value = appId.ToString();
 config.Save();

 上面的代码参考自 stackoverflow ,但是OpenMappedWebConfiguration 必须指定第3个参数,否则会报错。不过,siteName 并不要求与IIS的站点名字对应,随意写一个也可以。

 2,使用angularJS 绑定站点信息

首先定义一个 webSiteListApp HTML代码片断:

<div ng-app="webSiteListApp" class="container">
    <div ng-controller="webSiteListController">
        <ul>
            <li ng-repeat="item in siteList">
                站点名:{{item.SiteName}} ------绑定信息:{{item.DomainPort}}
            </li>
        </ul>
    </div>
</div>

然后定义module和service:

<script type="text/javascript">
    // 参考 http://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/05/13/how-to-use-angularjs-in-asp-net-mvc-and-entity-framework-4.aspx

    var webSiteListApp = angular.module("webSiteListApp", []);
    webSiteListApp.controller("webSiteListController", function ($scope, webSiteService) {
        getSiteList();
        function getSiteList() {
            var list = webSiteService.getSiteList()
            .success(function (sites) {
                $scope.siteList = sites;
                console.log($scope.siteList);
            })
            .error(function (error) {
                $scope.status = 'Unable to load customer data: ' + error.message;
                console.log($scope.status);
            });
          
        }
    });
    webSiteListApp.factory("webSiteService", ["$http", function ($http) {
        var webSiteService = {};
        webSiteService.getSiteList = function () {
            return $http.get("/SiteManage/GetServerBindings");
        }
        return webSiteService;
    }]);
</script>


这里定义了一个叫做 webSiteListApp 的module,然后注册一个 webSiteListController 的控制器,该控制器在前面的HTMl代码中定义,最后创建一个 webSiteService ,它监听后来MVC来的数据,该数据对应的ASP.NET MVC 方法如下:

        public JsonResult GetServerBindings()
        {
            var siteList = IISControlHelper.IISWorker.GetServerBindings();
            return Json(siteList, JsonRequestBehavior.AllowGet);
        }

3,IIS管理程序

可以创建,删除网站,添加应用程序池,代码如下:

using System;
using System.Collections;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace IISControlHelper
{
    /// <summary>
    /// IIS 操作方法集合
    /// http://blog.csdn.net/ts1030746080/article/details/8741399 错误
    /// </summary>
    public class IISWorker
    {
        private static string HostName = "localhost";

        /// <summary>
        /// 获取本地IIS版本
        /// </summary>
        /// <returns></returns>
        public static string GetIIsVersion()
        {
            try
            {
                DirectoryEntry entry = new DirectoryEntry("IIS://" + HostName + "/W3SVC/INFO");
                string version = entry.Properties["MajorIISVersionNumber"].Value.ToString();
                return version;
            }
            catch (Exception se)
            {
                //说明一点:IIS5.0中没有(int)entry.Properties["MajorIISVersionNumber"].Value;属性,将抛出异常 证明版本为 5.0
                return string.Empty;
            }
        }

        /// <summary>
        /// 创建虚拟目录网站
        /// </summary>
        /// <param name="webSiteName">网站名称</param>
        /// <param name="physicalPath">物理路径</param>
        /// <param name="domainPort">站点+端口,如192.168.1.23:90</param>
        /// <param name="isCreateAppPool">是否创建新的应用程序池</param>
        /// <returns></returns>
        public static int CreateWebSite(string webSiteName, string physicalPath, string domainPort,bool isCreateAppPool)
        {
            DirectoryEntry root = new DirectoryEntry("IIS://" + HostName + "/W3SVC");
            // 为新WEB站点查找一个未使用的ID
            int siteID = 1;
            foreach (DirectoryEntry e in root.Children)
            {
                if (e.SchemaClassName == "IIsWebServer")
                {
                    int ID = Convert.ToInt32(e.Name);
                    if (ID >= siteID) { siteID = ID + 1; }
                }
            }
            // 创建WEB站点
            DirectoryEntry site = (DirectoryEntry)root.Invoke("Create", "IIsWebServer", siteID);
            site.Invoke("Put", "ServerComment", webSiteName);
            site.Invoke("Put", "KeyType", "IIsWebServer");
            site.Invoke("Put", "ServerBindings", domainPort );
            site.Invoke("Put", "ServerState", 2);
            site.Invoke("Put", "FrontPageWeb", 1);
            site.Invoke("Put", "DefaultDoc", "Default.html");
            // site.Invoke("Put", "SecureBindings", ":443:");
            site.Invoke("Put", "ServerAutoStart", 1);
            site.Invoke("Put", "ServerSize", 1);
            site.Invoke("SetInfo");
            // 创建应用程序虚拟目录

            DirectoryEntry siteVDir = site.Children.Add("Root", "IISWebVirtualDir");
            siteVDir.Properties["AppIsolated"][0] = 2;
            siteVDir.Properties["Path"][0] = physicalPath;
            siteVDir.Properties["AccessFlags"][0] = 513;
            siteVDir.Properties["FrontPageWeb"][0] = 1;
            siteVDir.Properties["AppRoot"][0] = "LM/W3SVC/" + siteID + "/Root";
            siteVDir.Properties["AppFriendlyName"][0] = "Root";

            if (isCreateAppPool)
            {
                DirectoryEntry apppools = new DirectoryEntry("IIS://" + HostName + "/W3SVC/AppPools");

                DirectoryEntry newpool = apppools.Children.Add(webSiteName, "IIsApplicationPool");
                newpool.Properties["AppPoolIdentityType"][0] = "4"; //4
                newpool.Properties["ManagedPipelineMode"][0] = "0"; //0:集成模式 1:经典模式
                newpool.Properties["ManagedRuntimeVersion"][0] = "v4.0";
                newpool.CommitChanges();
                siteVDir.Properties["AppPoolId"][0] = webSiteName;
            }

            siteVDir.CommitChanges();
            site.CommitChanges();
            return siteID;
        }

        /// <summary>
        /// 得到网站的物理路径
        /// </summary>
        /// <param name="rootEntry">网站节点</param>
        /// <returns></returns>
        public static string GetWebsitePhysicalPath(DirectoryEntry rootEntry)
        {
            string physicalPath = "";
            foreach (DirectoryEntry childEntry in rootEntry.Children)
            {
                if ((childEntry.SchemaClassName == "IIsWebVirtualDir") && (childEntry.Name.ToLower() == "root"))
                {
                    if (childEntry.Properties["Path"].Value != null)
                    {
                        physicalPath = childEntry.Properties["Path"].Value.ToString();
                    }
                    else
                    {
                        physicalPath = "";
                    }
                }
            }
            return physicalPath;
        }

        /// <summary>
        /// 获取站点名
        /// </summary>
        public static List<IISInfo> GetServerBindings()
        {
            List<IISInfo> iisList = new List<IISInfo>();
            string entPath = String.Format("IIS://{0}/w3svc", HostName);
            DirectoryEntry ent = new DirectoryEntry(entPath);
        
            foreach (DirectoryEntry child in ent.Children)
            {
                if (child.SchemaClassName.Equals("IIsWebServer", StringComparison.OrdinalIgnoreCase))
                {
                    if (child.Properties["ServerBindings"].Value != null)
                    {
                        object objectArr = child.Properties["ServerBindings"].Value;
                        string serverBindingStr = string.Empty;
                        if (IsArray(objectArr))//如果有多个绑定站点时
                        {
                            object[] objectToArr = (object[])objectArr;
                            serverBindingStr = objectToArr[0].ToString();
                        }
                        else//只有一个绑定站点
                        {
                            serverBindingStr = child.Properties["ServerBindings"].Value.ToString();
                        }
                        IISInfo iisInfo = new IISInfo();
                        iisInfo.DomainPort = serverBindingStr;
                        iisInfo.AppPool = child.Properties["AppPoolId"].Value.ToString();//应用程序池,有可能不准确
                        object objComment=child.Properties["ServerComment"].Value;
                        if (objComment != null)
                        {
                            iisInfo.SiteName = objComment.ToString();
                        }
                        iisList.Add(iisInfo);
                    }
                }
            }
            return iisList;
        }


        public static bool CreateAppPool(string appPoolName, string Username, string Password)
        {
            bool issucess = false;
            try
            {
                //创建一个新程序池
                DirectoryEntry newpool;
                DirectoryEntry apppools = new DirectoryEntry("IIS://" + HostName + "/W3SVC/AppPools");
                newpool = apppools.Children.Add(appPoolName, "IIsApplicationPool");

                //设置属性 访问用户名和密码 一般采取默认方式
                newpool.Properties["WAMUserName"][0] = Username;
                newpool.Properties["WAMUserPass"][0] = Password;
                newpool.Properties["AppPoolIdentityType"][0] = "3";
                newpool.CommitChanges();
                issucess = true;
                return issucess;
            }
            catch // (Exception ex) 
            {
                return false;
            }
        }


        /// <summary>
        /// 建立程序池后关联相应应用程序及虚拟目录
        /// </summary>
        public static void SetAppToPool(string appname,string poolName)
        {
            //获取目录
            DirectoryEntry getdir = new DirectoryEntry("IIS://localhost/W3SVC");
            foreach (DirectoryEntry getentity in getdir.Children)
            {
                if (getentity.SchemaClassName.Equals("IIsWebServer"))
                {
                    //设置应用程序程序池 先获得应用程序 在设定应用程序程序池
                    //第一次测试根目录
                    foreach (DirectoryEntry getchild in getentity.Children)
                    {
                        if (getchild.SchemaClassName.Equals("IIsWebVirtualDir"))
                        {
                            //找到指定的虚拟目录.
                            foreach (DirectoryEntry getsite in getchild.Children)
                            {
                                if (getsite.Name.Equals(appname))
                                {
                                    //【测试成功通过】
                                    getsite.Properties["AppPoolId"].Value = poolName;
                                    getsite.CommitChanges();
                                }
                            }
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 判断object对象是否为数组
        /// </summary>
        public static bool IsArray(object o)
        {
            return o is Array;
        }
    }

    public class IISInfo
    {
        public string SiteName { get; set; }
        public string DomainPort { get; set; }
        public string AppPool { get; set; }

    }
}
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-03
  • 2021-08-22
  • 2021-12-09
猜你喜欢
  • 2021-08-15
  • 2021-11-20
  • 2021-05-02
  • 2022-02-20
  • 2021-09-17
  • 2021-07-05
  • 2021-09-22
相关资源
相似解决方案