zoukankan      html  css  js  c++  java
  • .net C# 程序控制IIS 添加站点域名绑定

    注意使用时要有服务器管理员权限 ,可在Web.config 添加

    <system.web>
          <identity impersonate="true" userName="服务器用户名"  password="密码" />
    </system.web>

    先添加两个引用:

    System.EnterpriseServices及System.DirectoryServices

    然后再在代码中引用:

    1 using System.DirectoryServices;
    2 using System.EnterpriseServices;

    然后就是如何添加绑定了:

     1      public static void AddHostHeader(int siteid, string ip, int port, string domain)//增加主机头(站点编号.ip.端口.域名)
     2         {
     3             DirectoryEntry site = new DirectoryEntry("IIS://localhost/W3SVC/" + siteid);
     4             PropertyValueCollection serverBindings = site.Properties["ServerBindings"];
     5             string headerStr = string.Format("{0}:{1}:{2}", ip, port, domain);
     6             log4net.LogManager.GetLogger("root").Info(serverBindings.PropertyName + serverBindings.Value.ToString());
     7             if (!serverBindings.Contains(headerStr))
     8             {
     9                 serverBindings.Add(headerStr);
    10             }
    11             site.CommitChanges();
    12         }

    其中,siteid,自己到IIS中看,ip不指定的话填"*",端口一般是80,域名是怎么多少就入多少
    注意:

    1、添加后,会自动重启站点;

    2、如果里面某个域名,重复添加,网站在重启的过程中会起不来,那就完蛋了,这个必须要配合自己的数据库;

    3、必须在web.config添加权限配置:
    ————————————————

    <system.web>
          <identity impersonate="true" userName="Administrator" password="password" />
      </system.web>

    4、如果在IIS7中出现: DirectoryEntry配置IIS7出现ADSI Error:未知错误(0x80005000)
    “控制面板”->“程序和功能”->面板左侧“打开或关闭windows功能”->“Internet信息服务”->“Web管理工具”->“IIS 6管理兼容性”->“IIS 元数据库和IIS 6配置兼容性”。更理想的解决方式是用 WMI provider操作IIS 7 ,可参见此篇文章http://msdn.microsoft.com/en-us/library/aa347459.aspx

    ————————————————
    版权声明:本文为CSDN博主「hejisan」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/hejisan/java/article/details/71156796

    其他方案:

    using System;
    
    using System.DirectoryServices;
    using System.EnterpriseServices;
    using System.Text.RegularExpressions;
    namespace WebCloud.Builder
    {
        public class IIS
        {
                    /// <summary>
            /// 获取最小ID,越小越好
            /// </summary>
            /// <returns></returns>
            public int SiteId()
            {
                DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
                // Find unused ID value for new web site
                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;
                        }
                    }
                }
                return siteID;
            }
            #region 建IIS站点
            /// <summary>
            /// IIS站点
            /// </summary>
            /// <param name="port">站点端口</param>
            /// <param name="siteName">站点ID</param>
            /// <param name="siteExplain">域名</param>
            /// <param name="defaultDoc">默认文档</param>
            public int  CreateSite(string port, string siteName, string siteExplain, string defaultDoc, string pathToRoot,string UserId)
            {
                int mark = 0;
                try
                {
                    // createAppPool(siteExplain);
                    DirectoryEntry de = new DirectoryEntry("IIS://localhost/" + "w3svc");   //从活动目录中获取IIS对象。  
                    object[] prams = new object[2] { "IIsWebServer", Convert.ToInt32(siteName) };
                    DirectoryEntry site = (DirectoryEntry)de.Invoke("Create", prams); //创建IISWebServer对象。  
                    site.Properties["KeyType"][0] = "IIsWebServer";
                    site.Properties["ServerComment"][0] = siteExplain; //站点说明  
                    site.Properties["ServerState"][0] = 2; //站点初始状态,1.停止,2.启动,3  
                    site.Properties["ServerSize"][0] = 1;
                    site.Properties["ServerBindings"].Add(":" + port + ":" + siteExplain); //站点端口  
                    site.CommitChanges(); //保存改变
                    de.CommitChanges();
                    DirectoryEntry root = site.Children.Add("Root", "IIsWebVirtualDir");   //添加虚拟目录对象  
                    root.Invoke("AppCreate", true); //创建IIS应用程序  
                    root.Invoke("AppCreate3", new object[] { 2, UserId, true });  //创建应用程序池,并指定应用程序池为"HostPool","true"表示如果HostPool不存在,则自动创建
                    root.Properties["path"][0] = pathToRoot; //虚拟目录指向的物理目录  
                    root.Properties["EnableDirBrowsing"][0] = true;//目录浏览  
                    root.Properties["AuthAnonymous"][0] = true;
                    root.Properties["AccessExecute"][0] = true;   //可执行权限  
                    root.Properties["AccessRead"][0] = true;
                    root.Properties["AccessWrite"][0] = true;
                    root.Properties["AccessScript"][0] = true;//纯脚本  
                    root.Properties["AccessSource"][0] = false;
                    root.Properties["FrontPageWeb"][0] = false;
                    root.Properties["KeyType"][0] = "IIsWebVirtualDir";
                    root.Properties["AppFriendlyName"][0] = siteExplain; //应用程序名   
                    root.Properties["AppIsolated"][0] = 2;
                    root.Properties["DefaultDoc"][0] = defaultDoc; //默认文档  
                    root.Properties["EnableDefaultDoc"][0] = true; //是否启用默认文档  
                    root.CommitChanges();
                    site.CommitChanges();
                    root.Close();
                    site.Close();
                    de.CommitChanges(); //保存  
                    site.Invoke("Start", null); //除了在创建过程中置初始状态外,也可在此调用方法改变状态  
                    mark = 1;
                }
                catch
                {
                    mark = 0;
                }
                return mark;
            }
            #endregion
            #region 域名绑定方法
            public int  AddHostHeader(int siteid, string ip, int port, string domain)//增加主机头(站点编号.ip.端口.域名)
            {
                int mark = 0;
                try
                {
                    DirectoryEntry site = new DirectoryEntry("IIS://localhost/W3SVC/" + siteid);
                    PropertyValueCollection serverBindings = site.Properties["ServerBindings"];
                    string headerStr = string.Format("{0}:{1}:{2}", ip, port, domain);
                    if (!serverBindings.Contains(headerStr))
                    {
                        serverBindings.Add(headerStr);
                    }
                    site.CommitChanges();
                    mark = 1;
                }
                catch
                {
                    mark = 0;
                }
                return mark;
            }
            #endregion
            #region 删除主机头
        public  void DeleteHostHeader(int siteid, string ip, int port, string domain)//删除主机头(站点编号.ip.端口.域名)
            {
                DirectoryEntry site = new DirectoryEntry("IIS://localhost/W3SVC/" + siteid);
                PropertyValueCollection serverBindings = site.Properties["ServerBindings"];
                string headerStr = string.Format("{0}:{1}:{2}", ip, port, domain);
                if (serverBindings.Contains(headerStr))
                {
                    serverBindings.Remove(headerStr);
                }
                site.CommitChanges();
            }
            #endregion
            #region 删除站点
            public void DelSite(string siteName)
            {
                string siteNum = GetWebSiteNum(siteName);
                string siteEntPath = String.Format("IIS://{0}/w3svc/{1}", "localhost", siteNum);
                DirectoryEntry siteEntry = new DirectoryEntry(siteEntPath);
                string rootPath = String.Format("IIS://{0}/w3svc", "localhost");
                DirectoryEntry rootEntry = new DirectoryEntry(rootPath);
                rootEntry.Children.Remove(siteEntry);
                rootEntry.CommitChanges();
            }
            public string GetWebSiteNum(string siteName)
            {
                Regex regex = new Regex(siteName);
                string tmpStr;
                string entPath = String.Format("IIS://{0}/w3svc", "localhost");
                DirectoryEntry ent = new DirectoryEntry(entPath);
                foreach (DirectoryEntry child in ent.Children)
                {
                    if (child.SchemaClassName == "IIsWebServer")
                    {
                        if (child.Properties["ServerBindings"].Value != null)
                        {
                            tmpStr = child.Properties["ServerBindings"].Value.ToString();
                            if (regex.Match(tmpStr).Success)
                            {
                                return child.Name;
                            }
                        }
                        if (child.Properties["ServerComment"].Value != null)
                        {
                            tmpStr = child.Properties["ServerComment"].Value.ToString();
                            if (regex.Match(tmpStr).Success)
                            {
                                return child.Name;
                            }
                        }
                    }
                }
                return "没有找到要删除的站点";
            }
            #endregion
            #region 创建应用程序池
            static void createAppPool(string AppPoolName)
            {
                DirectoryEntry newpool;
                DirectoryEntry apppools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
                newpool = apppools.Children.Add(AppPoolName, "IIsApplicationPool");
                newpool.CommitChanges();
            }
            #endregion
            #region 删除应用程序池
            public void deleteAppPool(string AppPoolName)
            {
                bool ExistAppPoolFlag=false;
                try
                {
                    DirectoryEntry apppools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
                    foreach (DirectoryEntry a in apppools.Children)
                    {
                        if (a.Name == AppPoolName)
                        {
                            ExistAppPoolFlag = true;
                            a.DeleteTree();
                           // MessageBox.Show("应用程序池名称删除成功", "删除成功");
                        }
                    }
                    if (ExistAppPoolFlag == false)
                    {
                       // MessageBox.Show("应用程序池未找到", "删除失败");
                    }
                }
                catch
                {
                    //MessageBox.Show(ex.Message, "错误");
                }
            }
            #endregion
        }
    }
    
    ————————————————
    版权声明:本文为CSDN博主「seekboya」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/seekboya/java/article/details/7569703
  • 相关阅读:
    SpringMVC—对Ajax的处理(含 JSON 类型)(2)
    md5加密(1)
    js生成邀请码(2)
    SpringMVC---依赖注入与面向切面
    初识json
    java集合类(2)
    springmvc与struts2的区别
    模拟14
    NOIP模拟13
    NOIP模拟12
  • 原文地址:https://www.cnblogs.com/riddly/p/13083095.html
Copyright © 2011-2022 走看看