When WebApi unit testing, generally requires an IIS site, the general approach is to be accomplished by writing a batch bat script, in fact, through coding, can achieve this functionality.
There are three main concerns: the application pool, Web sites, the binding (the protocol type: http, https, IP address, port, hostname)
1. General Code
var webSite = app.WebSite; the using ( var SM = new new the ServerManager ()) { // create an application pool var appPool = sm.ApplicationPools.FirstOrDefault (AP => ap.Name.Equals (webSite.PoolName)); IF ( == appPool null ) { CreateAppPool (sm.ApplicationPools, webSite.PoolName); } // Create a Web site var site = sm.Sites.FirstOrDefault (S => s.Name.Equals (webSite.SiteName)); IF (site == null ) { CreateWebSite(sm.Sites, webSite, app.InstallPath); } sm.CommitChanges(); }
2. Create an application pool:
/// <the Summary> /// Create an application pool /// </ the Summary> /// <param name = "AppPools"> </ param> /// <param name = "AppPoolName"> </ param> Private void CreateAppPool (ApplicationPoolCollection AppPools, String AppPoolName) { var appPool = appPools.Add (AppPoolName); // if self-starting appPool.AutoStart = to true ; // queue length appPool.QueueLength = 10000 ; // start mode appPool.StartMode =StartMode.AlwaysRunning; // recovery interval appPool.Recycling.PeriodicRestart.Time = new new TimeSpan (); // idle timeout appPool.ProcessModel.IdleTimeout = new new TimeSpan (); // maximum number of worker processes appPool.ProcessModel.MaxProcesses = 1 ; }
3. Create a site
/// <summary> /// 创建Web站点 /// </summary> /// <param name="sites"></param> /// <param name="webSite"></param> /// <param name="physicalPath"></param> private void CreateWebSite(SiteCollection sites, WebSite webSite, string physicalPath) { Site site = null; bool isSiteCreated = false; foreach (var binding in webSite.The binding) bin ding Info =were { ConstructBindingInfo(binding); if (!isSiteCreated) { site = sites.Add(webSite.SiteName, binding.BindingType, bingdingInfo, physicalPath); //是否自启动 site.ServerAutoStart = true; isSiteCreated = true; } else { site.Bindings.Add(bingdingInfo, binding.BindingType); } } var root = site.Applications["/"]; //Set application pool root.ApplicationPoolName = webSite.PoolName; // virtual directory // . Root.VirtualDirectories [ "/"] = PhysicalPath pathToRoot; // preload root.SetAttributeValue ( " preloadEnabled " , to true ); }
4. Create Binding
/// <summary> /// 构建绑定信息 /// </summary> /// <param name="binding"></param> /// <returns></returns> private string ConstructBindingInfo(WebSiteBinding binding) { var sb = new StringBuilder(); if (!string.IsNullOrEmpty(binding.IP)) { sb.Append(binding.IP); } else { sb.Append("*"); } sb.Append(":"); sb.Append(binding.Port); sb.Append(":"); if (!string.IsNullOrEmpty(binding.HostName)) { sb.Append(binding.HostName); } else { sb.Append(string.Empty); } return sb.ToString(); }
Reproduced in: https: //www.cnblogs.com/liugh/p/8684696.html