设为首页 收藏本站
查看: 934|回复: 0

[经验分享] 如何管理IIS,自动创建WEB SITE,应用程序池

[复制链接]

尚未签到

发表于 2015-8-13 11:18:07 | 显示全部楼层 |阅读模式
有时我们需要动态的创建WEB SITE或都是虚拟目录,比如,当用户申请一个社区后,分配一个二级域名的,一个用户一个Web site。这时我们就可以用到。NET访问IIS的功能,来自动创建了。
需要引用using System.DirectoryServices;这个组件来管理IIS,如果是WEB来访问的话还有权限的问题,一般这样并发的要求性能较高的操作都写成SERVICE后台来处理比较合适。
请看下面的代码片段,
/// <summary>
        /// 创建应用程序池
        /// </summary>
        /// <param name="AppPoolName"></param>
        public static void CreateAppPool(string AppPoolName)
        {
            bool ExistAppPoolFlag = false;
            DirectoryEntry newpool;
            DirectoryEntry apppools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
            foreach (DirectoryEntry a in apppools.Children)
            {
                if (a.Name == AppPoolName)
                {
                    ExistAppPoolFlag = true;
                    break;
                }
            }
            if (ExistAppPoolFlag == false)
            {
                newpool = apppools.Children.Add(AppPoolName, "IIsApplicationPool");
                newpool.CommitChanges();           
            }
        }
        /// <summary>
        /// 给某一个site分配程序池
        /// </summary>
        /// <param name="newvdir">The newvdir.</param>
        /// <param name="AppPoolName">Name of the app pool.</param>
        public static void AssignAppPool(DirectoryEntry newvdir, string AppPoolName)
        {
            newvdir.Properties["AppPoolId"].Value = AppPoolName;
            newvdir.CommitChanges();
        }
//下面这个是修改Web Site的执行脚本。 通常建一个web site default的asp.net 1.1
/// <summary>
        /// Updates the aspdotnet script version.
        /// </summary>
        /// <param name="UpdateScriptPath">The update script path.</param>
        public static void UpdateAspdotnetScriptVersion(DirectoryEntry siteVDir,string UpdateScriptPath)
        {
            string fileName = UpdateScriptPath;
            ProcessStartInfo startInfo = new ProcessStartInfo(fileName);
            if (startInfo != null)
            {
                //处理目录路径
                string path = siteVDir.Path.ToUpper();
                int index = path.IndexOf("W3SVC");
                path = path.Remove(0, index);
                //启动aspnet_iis.exe程序,刷新教本映射
                startInfo.Arguments = "-s " + path;
                startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                startInfo.UseShellExecute = false;
                startInfo.CreateNoWindow = true;
                startInfo.RedirectStandardOutput = true;
                startInfo.RedirectStandardError = true;
                Process process = new Process();
                process.StartInfo = startInfo;
                process.Start();
                process.WaitForExit();
                string errors = process.StandardError.ReadToEnd();
                if (errors != string.Empty)
                {
                    throw new Exception(errors);
                }
                process.Dispose();
            }         
        }
//创建一个web site的虚似目录
/// <summary>
        /// Createirtuals the directory.
        /// </summary>
        /// <param name="nameDirectory">The name directory.</param>
        /// <param name="VirDirSchemaName">Name of the vir dir schema.</param>
        public static void CreateirtualDirectory(string virtualDirName, string physicalPath, int webSiteID)
        {

            String constIISWebSiteRoot = "IIS://localhost/W3SVC/"+webSiteID+"/ROOT";
                     
            DirectoryEntry root = new DirectoryEntry(constIISWebSiteRoot);      
           
            DirectoryEntry tbEntry = root.Children.Add(virtualDirName, root.SchemaClassName);

            tbEntry.Properties["Path"][0] = physicalPath;//设置虚拟目录指向的物理路径
            tbEntry.Invoke("AppCreate2", false);//是否创建应用程序池
            //AccessRead,AccessWrite,AccessExecute,AccessScript,DefaultDoc,EnableDefaultDoc,Path
            tbEntry.Properties["AccessRead"][0] = true;////设置读取权限                       
            tbEntry.Properties["AccessWrite"][0] = true;
            tbEntry.Properties["AccessExecute"][0] = false;
            tbEntry.Properties["AccessScript"][0] = false;
            //tbEntry.Properties["ContentIndexed"][0] = true;
            tbEntry.Properties["AppIsolated"].Value = 2;
            tbEntry.Properties["EnableDefaultDoc"][0] = false;
            tbEntry.Properties["UNCPassword"][0] = "aa";
            tbEntry.Properties["UNCUserName"][0] = "bb";


            //设置访问的default document
            //tbEntry.Properties["DefaultDoc"][0] = "index.asp,Default.aspx";
            //tbEntry.Properties["AppFriendlyName"][0] = virtualDirName;//应用程序名称
            //tbEntry.Properties["AccessScript"][0] = false;//执行权限
            tbEntry.Properties["DontLog"][0] = true;
            //设置目录的安全性,0表示不允许匿名访问,1为允许,3为基本身份验证,7为windows继承身份验证
            tbEntry.Properties["AuthFlags"][0] = 3;           
            tbEntry.CommitChanges();
            root.CommitChanges();
        }
//创建一个新的Web site
        /// <summary>
        /// Creates a web site
        /// </summary>
        /// <param name="name">The name of the site</param>
        /// <param name="homeDirectory">The site's home direcotry</param>
        /// <param name="port">The web site's port</param>
        /// <returns>The newly created site</returns>
        public static IIsWebSite CreateWebSite(string name, string homeDirectory, int port,string CreateNewPool)
        {                        
            if (name == null || name.Length == 0)
            {
                throw new ArgumentException("You must specify a web site name");
            }

            if (homeDirectory == null || homeDirectory.Length == 0)
            {
                throw new ArgumentException("You must specify a home directory for the web site");
            }

            if (port < 0)
            {
                throw new ArgumentException("Your specified port must be greater then or equal to 0");
            }

            DirectoryEntry root = new DirectoryEntry(IIsConstants.IIsW3SvcPath);

            // Finds an open site ID (in IIs 5 it is sequential - in IIs 6 they are random) to try and make it
            // work for both, we will just find the largest current one and add one to it
            int siteID = 1;
            foreach(DirectoryEntry e in root.Children)
            {
                if(e.SchemaClassName == IIsConstants.IIsWebServerName)
                {
                    int ID = Convert.ToInt32(e.Name);
                    if(ID > siteID)
                    {
                        siteID = ID;
                    }
                }
            }

            siteID += 1;

            // Create the site
            DirectoryEntry site = (DirectoryEntry)root.Invoke("Create", IIsConstants.IIsWebServerName, siteID);
           
            site.Invoke("Put", "ServerComment", name);
            site.Invoke("Put", "KeyType", IIsConstants.IIsWebServerName);
            //site.Invoke("Put", "ServerBindings", ":" + port.ToString() + ":");
            site.Invoke("Put", "ServerState", 1);
            site.Invoke("Put", "FrontPageWeb", 1);
            site.Invoke("Put", "DefaultDoc", "default.aspx");
            //site.Invoke("Put", "SecureBindings", ":443:");//设置SSL
            site.Invoke("Put", "ServerAutoStart", 0);
            site.Invoke("Put", "ServerSize", 1);
            site.Invoke("Put", "AccessRead", true);
            site.Invoke("Put", "AccessScript", true);
            site.Invoke("Put", "AccessWrite", false);
            site.Invoke("Put", "EnableDirBrowsing", false);
            site.Invoke("Put", "AppFriendlyName", name);  
            site.Invoke("SetInfo");
           

            // Create the application virtual directory
            DirectoryEntry siteVDir = site.Children.Add("Root", "IIsWebVirtualDir");
            siteVDir.Properties["AppIsolated"][0] = 2;
            siteVDir.Properties["Path"][0] = homeDirectory;
            siteVDir.Properties["AccessFlags"][0] = 513;
            siteVDir.Properties["FrontPageWeb"][0] = 1;
            siteVDir.Properties["AppRoot"][0] = "/LM/W3SVC/" + siteID + "/Root";         
            siteVDir.CommitChanges();
            //site.CommitChanges();
            AddHostHeader(siteID, null, port, name);
            if (CreateNewPool.Length > 0)
            {
                CreateAppPool(CreateNewPool);
                AssignAppPool(site, CreateNewPool);
            }
            string Path =  Environment.GetEnvironmentVariable("windir") + @"\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe ";
            UpdateAspdotnetScriptVersion(site,Path);
            CreateirtualDirectory("album",@"\\192.168.1.10\FileUpLoad",siteID);
            // retrieve the entry for the site
            DirectoryEntry entry = new DirectoryEntry(IIsConstants.IIsW3SvcPath + "/" + siteID);
           

            // to make the site show up correctly we need to stop and start it, but we also
            // want to save the current started site
            IIsWebSite newWebSite = IIsWebSite.FromDirectoryEntry(entry);
            IIsWebSite currentWebSite = IIsAdministrator.GetWebSites().ActiveWebSite;

            if(currentWebSite != null)
            {               
                //currentWebSite.Stop();
                newWebSite.Start();
                //newWebSite.Stop();
                currentWebSite.Start();
            }         
            else
            {
                newWebSite.Start();
                newWebSite.Stop();
            }         

            // return a new wrapper around the site
            return newWebSite;
        }

问题:我可以正确的创建虚拟目录并指向一台远程的主机,把访问的username & password设置,但它始终是一个web application ,我不想让他成为一个application,只是一个文件夹虚拟目录用来指向远程主机。这个不知道用代码如何现实在
CreateirtualDirectory这个方法里,试过N次不行,有知道的请留言给我。谢谢
,/author]Leung[author]

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-98406-1-1.html 上篇帖子: IIS 请求处理过程 下篇帖子: 引用:CareySon--【译】在ASP.Net和IIS中删除不必要的HTTP响应头
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表